javascript - 如何在 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 但这个数组只有两个元素
谢谢你
解决方案
JavaScript 中的数组是标准对象,具有对称为数组索引的一类属性名称的特殊处理(名称都是规范整数形式的所有数字,其数值为>=
0 和<
2³²-1)、length
属性的特殊处理和使用Array.prototype
(通常)作为他们的原型。由数组索引名称命名的属性称为“元素”。其他属性只是属性。
数组的length
属性始终等于数组包含的最高数组元素索引加一。在您的第一个代码块中,没有数组元素(只有非元素属性),所以length
is 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;
}
推荐阅读
- javascript - 如何在从函数返回的地图中打印值
- networking - 重新连接后的 TCP Dup ACK - 序列号问题?
- python - 如何使用 pandas 对 Excel 文件中的数据进行排序。并对重复项进行排序
- terraform - Terraform 远程状态 - 使用计划/应用期间不存在的变量
- bash - bash脚本中意外标记附近的语法错误
- javascript - REACT - 未处理的拒绝(错误):无效的挂钩调用
- c# - 如何使用 CA 证书 C# 验证证书链
- regex - 在 AIML 聊天机器人程序 AB 中添加正则表达式
- laravel - 无法访问此站点花费了太长时间 - Laravel
- node.js - nodejs中套接字中的意外行为(双连接,