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前一項的初始值,並且沒有第三個參數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章