js中將類數組轉換為數組的幾種方法


js中將類數組轉換為數組的幾種方法

一、總結

一句話總結:

1、Array的slice方法,例如:Array.prototype.slice.call(arguments);
2、Array.from(),例如:let arr = Array.from(arguments);3、
3、擴展運算符...,例如:let arr = [...arguments];
4、jquery的$.makeArray(),例如:let arr = $.makeArray(arguments);

 

 

1、Array的slice方法將類數組對象轉換成數組?

a、let arr = Array.prototype.slice.call(arguments);
b、let arr1 = [].slice.call(arguments);
//1、slice方法 function f1() { console.log(arguments); //console.log(arguments instanceof Array); //console.log(arguments instanceof Object);  let arr = Array.prototype.slice.call(arguments); console.log(arr); let arr1 = [].slice.call(arguments); console.log(arr1); } f1(1,32,43,4);

 

 

2、Array.from()方法 將類數組對象轉換成數組?

let arr = Array.from(arguments);
//2、Array.from() function f1() { console.log(arguments); let arr = Array.from(arguments); console.log(arr); } f1(1,32,43,4);

 

 

3、擴展運算符... 將類數組對象轉換成數組?

let arr = [...arguments];
//3、擴展運算符... function f1() { console.log(arguments); let arr = [...arguments]; console.log(arr); } f1(1,32,43,4);

 

 

4、jquery的$.makeArray() 將類數組對象轉換成數組?

let arr = $.makeArray(arguments);
//4、jquery的$.makeArray() function f1() { console.log(arguments); let arr = $.makeArray(arguments); console.log(arr); } f1(1,32,43,5);

 

 

 

二、js中將類數組轉換為數組的幾種方法

轉自或參考:js中將類數組轉換為數組的幾種方法_JavaScript_(づ。◕‿‿◕。)づgigi奮斗在前端和刷題中╮(╯﹏╰)╭-CSDN博客
https://blog.csdn.net/crystal6918/article/details/60467615

slice

最經典的方法,使用Array的slice方法,此方法如果不傳參數的話會返回原數組的一個拷貝,因此可以用此方法轉換類數組到數組;

var arr = Array.prototype.slice.call(arguments);

//等同於

var arr = [].slice.call(arguments)

 

Array.from()

是ES6中的方法,用於將類數組轉換為數組。

var arr = Array.from(arguments);

只要有length屬性的對象,都可以應用此方法轉換成數組。

 

擴展運算符

ES6中的擴展運算符...也能將某些數據結構轉換成數組,這種數據結構必須有遍歷器接口。

var args = [...arguments];

 

$.makeArray()

jQuery的此方法可以將類數組對象轉化為真正的數組

var arr = $.makeArray(arguments);
 
 
 
 
 


免責聲明!

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



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