如何在 JavaScript 中获取对象的长度?
javascriptobject oriented programmingfront end technology更新于 2025/4/19 23:40:17
length 属性仅适用于数组 和字符串。因此,当我们在对象 上调用length 属性时,我们将得到undefined。
示例
<html>
<body>
<script>
var object = {prop:1, prop:2};
document.write(object.length);
</script>
</body>
</html>
输出
undefined
而数组和字符串在使用length属性时将显示其长度。
示例
<html>
<body>
<script>
var string = 'hello';
var array = [1,2,3];
var len1 = string.length;
var len2 = array.length;
document.write(len1);
document.write("</br>");
document.write(len2);
</script>
</body>
</html>
输出
5 3
在 javascript 中,我们有 Object.keys() 属性,用于检查是否有任何属性。如果我们将 length 属性与 Object.keys() 结合使用,则将显示属性的数量,该数量只是对象的长度。
示例
<html>
<body>
<script>
var object = {one: 1, two:2, three:3};
document.write(Object.keys(object).length);
</script>
</body>
</html>
输出
3
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

