arr.length获取的是真实长度吗:
var arr=new Array(10)
console(arr.length) // 10
1. 以上代码获得的数组长度是10.其实数组实际不为undefined的长度是0啊。
var a = [];
a['age'] = '18';
a['sex'] = 'Male';
console.log(a.length); // 0
2. 获得的数组长度是0. 其实数组实际不为undefined的长度是2啊。
再来看看对象长度
var a = {'age':30,'sex':'male'};
console.log(a.length); //undefined
所以长度要怎么获取呢?
es6新方法一招搞定: Object.keys(obj).length,毕竟数组也是特殊的对象嘛
var arr = new Array(10)
console.log(Object.keys(arr).length) // 0
var a = [];
a['age'] = '18';
a['sex'] = 'Male';
console.log(Object.keys(a).length); //2
var b = {
'age': 30,
'sex': 'male'
};
console.log(Object.keys(b).length); //2
也可以通过数组API for in等
function getObjLength(obj) {
if (typeof obj == "string") {
return obj.length;
}
var j = 0;
for (var i in obj) {
j++;
}
return j;
}
var arr = new Array(10)
console.log(getObjLength(arr)) // 0
var a = [];
a['age'] = '18';
a['sex'] = 'Male';
console.log(getObjLength(a)); //2
var b = {
'age': 30,
'sex': 'male'
};
console.log(getObjLength(b)); //2
getObjLength(null) //0 因为typeof null 也是object
扩展:Object.getOwnPropertyNames
var arr = ["a", "b", "c"];
console.log(Object.getOwnPropertyNames(arr)) // ["0", "1", "2", "length"]
Object.getOwnPropertyNames(arr).length //4
再扩展定义二维数组
var images = []; //先声明一维bai
for (var i = 0; i < 2; i++) { //一维长度为2
images[i] = new Array(); //在声明二维
for (var j = 0; j < 2; j++) { //二维长度为2
images[i][j] = i.toString() + j;
}
}
获取二维数组长度,不管值是不是undefind,则
images.length
images[0].length