如何从此阵列中删除Bob并刷新数组键,以便在删除Bob后Charlie键变为0而不是1?
//Insert: OK
var cars = [];
cars[cars.length] ="Bob";
cars[cars.length] ="Charlie";
cars[cars.length] ="Laura";
console.log( cars );
//Update: OK
function Update(input, upgrade) {
for(var key in cars) {
if(cars[key]===input) {
cars[key] = upgrade;
}
}
}
Update("Bob", "Bob-sleeping");
console.log( cars );
// Now removing Bob-sleeping from the array which should show Charlie and Laura
答案 0 :(得分:4)
使用splice
:
cars.splice(0, 1);
0
是删除条目的索引,1
是要删除的条目数。
"use strict";
var cars = [];
cars[cars.length] ="Bob";
cars[cars.length] ="Charlie";
cars[cars.length] ="Laura";
display("Before: " + cars.join(", "));
cars.splice(0, 1);
display("After: " + cars.join(", "));
function display(msg) {
var p = document.createElement("p");
p.innerHTML = String(msg);
document.body.appendChild(p);
}

如果您需要查找索引,即使是模糊的现代浏览器,您也可以使用indexOf
(可以在真正的旧版本上进行填充)。因此,如果您从"Bob-sleeping"
开始,那么:
var index = cars.indexOf("Bob-sleeping");
if (index !== -1) {
cars.splice(index, 1);
}
"use strict";
var cars = [];
cars[cars.length] ="Bob";
cars[cars.length] ="Charlie";
cars[cars.length] ="Laura";
display("Before: " + cars.join(", "));
var index = cars.indexOf("Bob"); // Or "Bob-sleeping", if you've `Update`d
if (index !== -1) {
cars.splice(index, 1);
}
display("After: " + cars.join(", "));
function display(msg) {
var p = document.createElement("p");
p.innerHTML = String(msg);
document.body.appendChild(p);
}