我有一个数组,里面放着牌 table ,但是删除后,数组的长度还是一样的。
var cards = ["1H", "2H", "3H", "4S", "5C", "6D"];
console.log("Cards Count: " + cards.length); // return 6
delete cards[3]; // return true
console.log("Cards Count: " + cards.length); // still returning 6
最佳答案
您需要使用 splice
而不是 delete
来删除数组中的项目。这是因为使用 delete
不会改变数组的长度。
这就是为什么长度仍然相同的原因,因为 undefined
项目仍然被计算在内。
var cards = ["1H", "2H", "3H", "4S", "5C", "6D"];
console.log("Cards Count: " + cards.length); // return 6
//delete cards[3]; // return true
cards.splice(3,1);
console.log(cards);
console.log("Cards Count: " + cards.length); // still returning 6
关于javascript - 删除后数组长度不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52108742/