1 回答
TA贡献1821条经验 获得超4个赞
您可以将属性的值移动 1
let data = {
info_0: 'abc',
info_1: 'def',
info_2: 'ghi',
info_3: 'jkl',
info_4: 'mno',
info_5: 'pqr'
},
input = document.querySelector("#index"),
button = document.querySelector("#remove"),
output = document.querySelector("#output");
button.addEventListener("click", () => removeItem(+input.value));
refreshOutput();
function removeItem(index) {
if (isNaN(index) || index < 0) return;
index = Math.floor(index);
while (data["info_" + index] !== undefined) {
data["info_" + index] = data["info_" + ++index];
}
refreshOutput();
}
function refreshOutput() {
output.textContent = JSON.stringify(data);
}
<input id="index" type="number" placeholder="index" />
<button id="remove">Remove</button>
<div id="output"></div>
您也可以使用delete运算符(效率很低)
let data = {
info_0: 'abc',
info_1: 'def',
info_2: 'ghi',
info_3: 'jkl',
info_4: 'mno',
info_5: 'pqr'
},
input = document.querySelector("#index"),
button = document.querySelector("#remove"),
output = document.querySelector("#output");
button.addEventListener("click", () => removeItem(+input.value));
refreshOutput();
function removeItem(index) {
if (isNaN(index) || index < 0) return;
index = Math.floor(index);
while (("info_" + index) in data) {
data["info_" + index] = data["info_" + ++index];
}
delete data["info_" + index];
refreshOutput();
}
function refreshOutput() {
output.textContent = JSON.stringify(data);
}
<input id="index" type="number" placeholder="index" />
<button id="remove">Remove</button>
<div id="output"></div>
或者你可以只使用一个数组和Array#splice
let data = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr'],
input = document.querySelector("#index"),
button = document.querySelector("#remove"),
output = document.querySelector("#output");
button.addEventListener("click", () => removeItem(+input.value));
refreshOutput();
function removeItem(index) {
if (isNaN(index) || index < 0) return;
data.splice(Math.floor(index), 1);
refreshOutput();
}
function refreshOutput() {
output.textContent = JSON.stringify(data);
}
<input id="index" type="number" placeholder="index" />
<button id="remove">Remove</button>
<div id="output"></div>
添加回答
举报