js - 偽數組轉化為數組的幾種方法整理


偽數組:無法調用數組的方法,但是有length屬性,又可以索引獲取內部項的數據結構。

比如:arguments、getElementsByTagName等一系列dom獲取的NodeList對象,他們 都算。
 
轉換方法
 
一:
假設這里有個偽數組:pagis
let arr = [].slice.call(pagis)

console.log(arr)   這時arr就是真數組了。

 

二:

let arr  = Array.prototype.slice.call(pagis);

利用了slice傳一個數組/集合,就會直接返回這個集合的原理。拿到的也是數組。

也就可以使用數組的各種方法了。

 

三:

1 var arr1 = [],
2   len1 = pagis.length;
3 for (var i = 0; i < len1; i++) {
4   arr1.push(pagis[i]);
5 }

就是簡單的for循環,把類數組的每一項都push到真正的數字arr1中

與之類似的另一種寫法:
(轉換函數中的arguments偽數組為真數組,是在學習es6時,將擴展運算符的收集功能在經過babel轉換后得到的es5代碼)

1 for (var _len = arguments.length, arr = new Array(_len), _key = 0; _key < _len; _key++) {
2     arr[_key] = arguments[_key];
3 }

 

 

 

四:

1 var func = Function.prototype.call.bind(Array.prototype.slice);
2 console.log('類數組轉換成數組:', func(pagis));

 

 五:...解構賦值

1 function args(){
2   console.log(arguments);
3   let newArr = [...arguments];
4   console.log(newArr);
5 }
6 args(1,2,3,23,2,42,34);

 

 

  六:Array.from

1 function args(){
2   console.log(arguments);
3   let newArr2 = Array.from(arguments);
4   console.log(newArr2);
5 }
6 args(1,2,3,23,2,42,34);

 

 

 

 

2019-05-07 16:48:27

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM