ES6数组及数组方法

时间:2023-03-09 14:37:38
ES6数组及数组方法

  ES6数组可以支持下面的几种写法:

(1)var [a,b,c] = [1,2,3];
(2)var [a,[[b],c]] = [1,[[2],3]];
(3)let [x,,y] = [1,2,3]; //x=1 y=3
(4)var [x,...y] = [1,2,3,4]; //x=1 y=[2,3,4]

  当然我认为代码必须要有易读性,所以请谨慎选择写法。

  下面就要说数组的方法
   转换成数组的方法Array.from()这个方法是把类似数组的对象或者是可遍历的对象转化为数组(包括了ES6里面的Set和Map方法)如果参数是一个数组则会返回一个一模一样的数组,这个方法如果传入的是一个字符串那么他会把传入的字符串拆开并返回。
  代码示例
var shuzu = {
'0' : "h",
'1' : "e",
'2' : "l",
'3' : "l",
'4' : "o",
length : 3,//要输出的长度
};
console.log(Array.from(shuzu)); //[ 'h', 'e', 'l' ]
console.log(Array.from(shuzu).length); //
console.log(Array.from('apple')); //[ 'a', 'p', 'p', 'l', 'e' ]
console.log(Array.from('apple').length); //

  如果是将一堆值转化为数组使用Array.of()

console.log(Array.of(1,2,3));//[ 1, 2, 3 ]
console.log(Array.of(1,2,3).length);//

  如果是复制当前数组某值到当前数组的某个位置使用copyWithin()会返回一个新的数组,接受三个参数依次为从该位置开始替换数据、从该位置开始读取数据和到该位置前停止读取数据。

console.log([0,1,2,3,4,5,6].copyWithin(0));    //[ 0, 1, 2, 3, 4, 5, 6 ]
console.log([0,1,2,3,4,5,6].copyWithin(0,2)); //[ 2, 3, 4, 5, 6, 5, 6 ]
//舍弃第二位以前的后面的补位并把后位用最后的两位补齐
console.log([0,1,2,3,4,5,6].copyWithin(0,2,3)); //[ 2, 1, 2, 3, 4, 5, 6 ]
//把原第三位补至原第零位其他位不变
console.log([0,1,2,3,4,5,6].copyWithin(0,2,4)); //[ 2, 3, 2, 3, 4, 5, 6 ]
//把原第二位第三位补至原第零位和第一位
console.log([0,1,2,3,4,5,6].copyWithin(0,2,5)); //[ 2, 3, 4, 3, 4, 5, 6 ]
//把原第二三四位补至原第零一二位

  判断该数组是否含有某值使用find()方法,这个方法有三个参数value(寻找的值)、index(从哪开始)、arr(原数组),这个方法用于找出第一个符合条件的数组成员并返回该值

console.log([1,2,3,4].find((n) => n<4));    //
console.log([1,2,3,4].find(function (value,index,arr) {return value<4 ;})); //

  如果要把数组内部全部替换并返回一个新的数组使用fill()方法,这个方法接受三个参数value(要填充的值)、start(从哪里填充)、end(填充到哪)。

console.log([1,2,3].fill('a'));    //[ 'a', 'a', 'a' ]
console.log([0,1,2].fill('a',1,3)); //[ 0, 'a', 'a' ]
//如果结束位大于等于数组的长度那么会从开始为到结束位都填充上填充的值 console.log([0,1,2,3,4].fill('a',1,3)); //[ 0, 'a', 'a', 3, 4 ]
/*也可以这么写*/
console.log(new Array(3).fill('a')); //[ 'a', 'a', 'a' ]

  如果你要遍历数组那么有三个方法可供选择entries()、keys()、values(),都返回一个遍历器对象,可以用for...of循环遍历,他三个不同的是keys()对键名的遍历,values()是对值的遍历,entries()是对键值对的遍历。

for(let index of [ 'test' , 'ceshi' , 'apple' ].keys()){ console.log(index); } // 0    1    2
for(let [index,values] of [ 'test' , 'ceshi' , 'apple' ].entries()){ console.log(index,values); }//0 'test' 1 'ceshi' 2 'apple'
for(let values of [ 'test' , 'ceshi' , 'apple' ].values()){ console.log(values); } //报错!!!也不知道为什么我的不支持这个函数,如果有发现这个问题怎么解决请在后面留言 Thanks?(?ω?)?

  如果查看数组里面是否含有某值使用includes()他会返回一个布尔值,有两个参数values(值)、start(从第几个开始)。

console.log([1,2,3].includes(1));//true
console.log([1,2,3].includes(1,2));//false

  数组推导允许直接通过现有的数组生成新的数组,有点像vue里面的 x of y

var nums = [1,2,3,4,5,6];
for (num of nums) if(num>2){ console.log(num); } ; //3 4 5 6