1.Array类上的方法
//Array(),将传进来的值编程数组返回
///注意:只传一个参数n,代表返回数组的长度
console.log(Array(1,2,4,5));//[1, 2, 4, 5]
console.log(Array(4));//[empty × 4]
//Array.of(),跟Array一样,只有一点区别就是传一个参数时候就是当前参数组成的数组
//Array.from()参数:数组或类数组,返回值是一个新的数组
function toArray() {
return Array.from(arguments);
}
console.log(toArray(1, 2, 4, 5));//[1,2,4,5]
2.Array原型上的方法扩展
//copyWithin(target,start,end)
//target: 必填,从该位置开始替换数据
//start:选填默认0,从该位置开始读取数据
//end:选填默认数组的长度,到该位置前停止读取数据
//注:超出部分不要,不会改变数组长度, 会改变原数组
let ary=[1,2,3,4,5,6,7,8];
console.log(ary.copyWithin(2));//[1, 2, 1, 2, 3, 4, 5, 6]
console.log(ary);//[1, 2, 1, 2, 3, 4, 5, 6]
//find(先遍历数组,一项一项的执行,一旦返回值是true,停止查找,返回当前项,一直到最有一项还没找到,最终结果返回undefined)
console.log(ary.find(function (item,index,input) {
//item 当前项 ,index索引,input 原数组
return item==4;
}))//4
//findIndex 返回值是当前的索引,如果没有,就返回-1
//fill(value,start,end):填充数组的
//value:必填,填充的值
//start:选填,开始填充的位置
//end:选填,停止填充的位置,不包括
let ary2=[1,2,3,4,5];
console.log(ary2.fill(1));//[1, 1, 1, 1, 1]
//得到有7个1的数组
console.log(Array(7).fill(1));//[1, 1, 1, 1, 1, 1, 1]
//includes :判断数组中有没有某一项,返回值是true/false
//indexOf lastIndexOf
console.log(ary2.includes(1));//true
3.数组的空位
var ary1=Array(3);
var ary2=[undefined,undefined,undefined];
console.log(1 in ary1);
console.log(1 in ary2);
var ary3=[1,,1,,]
console.log(ary3.length);//4
//ES5中的方法对空位处理都不太一致,大部分都是跳过空位的
console.log(ary3.map(function (item) {
return item;
}));//[1, empty, 1, empty]
//ES6,对空位的处理为undefined
ary3.find(function (item) {
console.log(1);//输出4次1
})
4.遍历数组
//for of
let arr = [2, 2, 3, 4, 5];
for (var key in arr) {
console.log(key) //当前索引
}
for (let index of arr) {
console.log(index);//输出当前项
}
//keys() 当前索引
for (let index of arr.keys()) {
console.log(index);//输出当前项
}
//entries()全部遍历出来
for (let [index,item] of arr.entries()) {
console.log(index,item);//输出所有
}