我有一个存放卡片的数组,但删除后,数组长度仍然相同。
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
数组是固定长度的。声明数组时,JVM会为您的数组分配特定大小(例如6)。即使从数组中删除值,数组的长度也不会改变。
如果您想要动态更改数组,可以尝试使用ArrayList,它是一个集合,但它可以作为动态数组使用。
您可以使用splice方法在JavaScript中添加/删除数组项。
例如:
加入array.splice(arrayIndex, No of Element to be removed, "xx", "yy");
array.splice(arrayIndex, No of Element to be removed);
删除
var cards = ["1H", "2H", "3H", "4S", "5C", "6D"];
console.log(cards.length); // 6
cards.splice(2, 1); // removes 3rd element of array
console.log(cards); // ["1H", "2H", "4S", "5C", "6D"];
console.log(cards.length); // 5
cards.splice(2, 0, "xx", "yy");
console.log(cards); // ["1H", "2H", "4S", "5C", "6D"];
console.log(cards.length); // 5