数组是按次序依次排列的一组值
const arr = [0,'1',{},function(){}]; //二维数组 const arr1 = [1,2,[3,4,5],6];
数组是一种特殊的对象,数组的key是正整数字符串,我们一般使用数字键操作数组,会自动转换成字符串
const arr = []; arr['1'] = 1; //1被自动转换成'1' console.log(arr[1],arr['1']); //1 typeof arr; //obejct
数组的length计算的是数组中正整数的个数,但你依然可以将数据的key设置为其它类型的值,不过这不会增加length的长度
const arr = []; arr[2.1] = 2.1; arr['a'] = 'a'; console.log(arr); //[2.1: 2.1, a: 'a'] console.log(arr.length); //0
length是可写的
const arr = [1,2,3,4,5]; arr.length = 2; console.log(arr); //[1,2]
in关键用来判断数组中存在某个键,可应用于数组和对象
const arr = ['a','b']; 1 in arr; // true 2 in arr; //fasle
const arr = [1,2]; arr['a'] = 3; arr[4.5] = 4; for(key in arr){ console.log(key); }; // 0 // 1 // a / 4.5 Object.keys(arr); // ['0', '1', 'a', '4.5']
var arr = [1,5,,8]; console.log(arr); //[1, 5, empty, 8] //使用delete也会产生空值 delete arr [0]; console.log(arr); //[empty, 5, empty, 8] console.log(arr.length); //4
const arr1 = new Array(10); //[empty × 10] for (key in arr1) { console.log(arr1); }; //无输出,没有进行遍历 arr1.forEach((v) => { console.log(v) }); //无输出,没有进行遍历 console.log(Object.keys(arr1)); //[] const arr2 = [undefined, undefined, undefined]; //[empty × 10] for (key in arr2) { console.log(key); }; //0 //1 //2 arr2.forEach((value, index) => { console.log(value, index) }); // undefined,0 // undefined,1 // undefinef,2 console.log(Object.keys(arr2)); //[3] // 使用for循环遍历empty for(let i = 0;i<arr1.length;i++){ console.log(arr1[1]) }; //undefined × 10
类数组的定义:键名都是正整数或零,拥有length属性
const arrayLike = { 0:'a', 1:'b', 2:'c', length:3 }; arrayLike[3] = 'd'; console.log(arrayLike[0]); //a console.log(arrayLike.length); //3
上面的代码为arrayLike添加了一个数字键,但length没有改变,这就说明arrayLike不是数组
典型的类数组有函数的arguments、大多数的元素DOM集合、字符串
function foo(){ console.log(arguments); }; foo('tom','jack'); // {0:'tom', 1:'jack', length:2, callee:...} console.log(document.getElementsByClassName('a')); //{"0": ...,"1": ...,"2":..., "length":3} const str = 'apple'; console.log(str.length); //5 consoel.log(str[2]); //p
将伪数组转为数组
function foo(){ const arr = Array.prototype.slice.call(arguments); } function foo(){ const arr = [...arguments] } function foo(...args){ }