首页 > 解决方案 > 如何在 javascript 中知道我的数组的长度

问题描述

我在 JavaScript 中有这段代码

    var items_in_cart = [];
    items_in_cart['rr'] = 1;
    items_in_cart['mm'] = 2;
alert(items_in_cart.length);

我得到 0

如果将代码更改为

items_in_cart[50] = 1;
items_in_cart[77] = 2;

我得到 78 但这个数组只有两个元素

谢谢你

标签: javascripthtmlarrays

解决方案


JavaScript 中的数组是标准对象,具有对称为数组索引的一类属性名称的特殊处理(名称都是规范整数形式的所有数字,其数值为>=0 和<2³²-1)、length属性的特殊处理和使用Array.prototype(通常)作为他们的原型。由数组索引名称命名的属性称为“元素”。其他属性只是属性。

数组的length属性始终等于数组包含的最高数组元素索引加一。在您的第一个代码块中,没有数组元素(只有非元素属性),所以lengthis 0. 在您的第二个中,最高数组元素索引是77,所以length也是78

如果您要在第一个代码块中使用非数组元素属性,通常最好使用非数组对象 ( {}),而不是数组[]

如果您想知道一个对象有多少个属性,您可以使用Object.keys(如果您不关心继承或不可枚举的属性)。这足以让您2获得初始代码块:

const items_in_cart = {}; // I've made this a non-array object
items_in_cart['rr'] = 1;
items_in_cart['mm'] = 2;
console.log(Object.keys(items_in_cart).length); // 2

或者您可以使用Object.getOwnPropertyNames(对于以字符串命名的)和/或Object.getOwnPropertySymbols(对于以符号命名的),它们也不包括继承的属性,但包括不可枚举的属性。您可以使用for-in循环获取所有继承的可枚举属性的计数。要获得所有属性的计数(无论是自己的还是继承的,可枚举的还是不可枚举的),您必须使用getOwnPropertyNames和/或getOwnPropertySymbols在对象上编写一个循环,然后使用Object.getPrototypeOf它转到其原型对象,依此类推,直到您到达原型链的末端。

如果你想知道一个稀疏数组(比如你的第二个)有多少个元素,这是我可能会使用的少数地方之一reduce(可能通过将它包装在一个有用的名称的函数中,例如getSparseCount):

function getSparseCount(array) {
    // `reduce` only visits existing elements, not holes in a sparse array
    const count = theArray.reduce(c => c + 1, 0);
    return count;
}

const items_in_cart = [];
items_in_cart[50] = 1;
items_in_cart[77] = 2;
console.log(getSparseCount(items_in_cart));

function getSparseCount(array) {
    // `reduce` only visits existing elements, not holes in a sparse array
    const count = array.reduce(c => c + 1, 0);
    return count;
}


推荐阅读