ES6中关于数组原型方法的扩展

本文只是限于自己的理解,可能也有很多不足或者不正确的地方,希望大家多多指正~

1.copyWithin(index,index1,index2);

从原数组中读取内容,替换数组中指定位置的内容

参数:index:从index索引开始替换

           index1:替换的内容从index1开始

           index2:替换的内容从index2结束但不包括index2(数组中涉及到的索引范围没有特别说明,一般都是左闭右开)

注意:此方法会改变原数组,并且当有超出部分时,自动截取,保持原数组长度不变

<script>
       let ary1=[1,2,3,4];
       let res1=ary1.copyWithin(2,0,3);
       console.log(res1);//[1,2,1,2]
</script>

2.fill("item",index1,index2);

按照指定字符填充数组

参数:item:用item来填充数组

          index1:填充开始的位置(可选)

          index2:填充结束的位置(可选)

         若只有一个参数item,则数组内容全部替换填充为item;

<script>
        let ary2=[5,8,9,7,45];
	let res2=ary2.fill("哈哈",2,6);
	console.log(res2);//[5, 8, "哈哈", "哈哈", "哈哈"]
</script>

3.filter(callback)

遍历数组,根据返回值过滤原数组,返回true留下当前项,返回false删除当前项

此方法不会改变原数组,返回一个新数组

<script>
       let ary3=[1,"哈哈",5,7,"啦啦",11];
       let res3=ary3.filter(function(item,index){
	  return typeof item!="string";
       });
       console.log(res3);// [1, 5, 7, 11]
</script>

4.find(callback)

先遍历数组,一旦数组函数返回true,停止查找,返回当前项;

<script>
       let ary4=[1,9,5,8,"啦啦",11,12];
       let res4=ary4.find(function(item,index){
	   return item%3;
       });
       console.log(res4); //1
</script>

findIndex用法与find一致,但是返回的是当前索引,而find返回的是当前项

5.reduce(callback,init)迭代

前一项与当前项的迭代

第二个参数:prev的初始值;(可选)

<script>
       let ary8=[9,27,8,11,12];
       let res8=ary8.reduce(function(prev,item){
	   return prev+item;
       },10)
       console.log(res8);
</script>

reduceRight 跟reduce一样,只是顺序从右开始

6.keys()遍历

每一项索引的接口,一般使用for of 遍历

<script>
        let ary9=[1,2,5,4,7];
	for (let key of ary9.keys()){
	      console.log(key);//0 1 2 3 4
	};
</script>

for of 遍历数组,默认遍历每一项

7.entries()遍历接口,可以遍历到索引和每一项(可以使用解构)

<script>
        let ary10=[1,3,5,4,7];
	for (let i of ary10.entries()){
	     console.log(i);//打印出来的是对象,有key和value
	}
	for (let [index,item] of ary10.entries()){
	    console.log(item);//打印出来的是数组中的每一项
	}
</script>

注意:遍历数组的方法,参数是函数,函数中this指向的是window,如果想改变this的指向,可以用第二个参数来改变this的指向,但reduce除外,因为reduce第二个参数是prev前一项的初始值,并且没有第三个参数。

猜你喜欢

转载自blog.csdn.net/weixin_39535289/article/details/80914180
今日推荐