是否可以在不重新排列索引且不将该位置更改为未定义的情况下删除某个位置的数组元素?
我不认为删除和拼接是可能的?
我需要一种准确的方法来查看数组的长度,而无需重新排列索引。
我不想使用拼接,因为我有一个对象,该对象的特定位置映射到表格 (Punkt) 的实际 X、Y 点。
更新:实际上,知道数组元素是否只存在于未定义的值中也可能对我有帮助,有没有比循环更简单的方法?
var keys = Object.keys(racks);
for (var i = 0; i < keys.length; i++)
{
for (var x = 0; x < racks[keys[i]].punkt.length; x++)
{
if(racks[keys[i]].punkt[x].y == fullName)
{
//delete racks[keys[i]].punkt[x];
racks[keys[i]].punkt.splice(x,1);
console.log(keys[i] + " : " + racks[keys[i]].punkt.length);
}
}
}
最佳答案
I don't think that is possible with delete nor splice?
I need an accurate way to view the length of the array, without rearranging indexes.
然后 delete
,一个 hasOwnProperty
或 in
守卫从数组中检索时,和一个循环计算元素(或一个单独的变量保持track) 是唯一的方法。 JavaScript 的标准数组本质上是稀疏(因为它们是 not really arrays at all ),它们在没有条目的地方可以有间隙。要创建间隙,请使用 delete
删除数组条目。
例子:
// Setup
var a = ["a", "b", "c", "d"];
console.log(a.length); // 4
// Using delete
delete a[2]; // Delete the entry containing "c"
console.log(a.length); // Still 4
a.hasOwnProperty(2); // false
// Using the guard when getting an entry
if (a.hasOwnProperty(2)) { // Or `if (2 in a)`
// Get and use [2]
}
else {
// Do whatever it is you want to do when the array doesn't have the entry
}
// Finding out how many it *really* has:
var key;
var count = 0;
for (key in a) {
if (a.hasOwnProperty(key) && // See below
/^0$|^[1-9]\d*$/.test(key) &&
key <= 4294967294
) {
++count;
}
}
console.log(count); // 3
参见 this other answer有关循环中 if
背后的详细信息。如果您从不在数组上放置非元素属性,则可以跳过 if
的第二和第三部分。
关于javascript - 如何删除没有拼接且没有未定义剩余的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20473526/