僞數組轉數組的幾種方式

將類數組轉換未數組的幾種方法
1. Array.prototype.slice.call()
function sum(a,b,c) {
    let args = Array.prototype.slice.call(arguments)
    console.log(args.reduce((sum, cur) => sum + cur))
}
sum(1 + 3 + 4)  //8
View Code
 2.Array.form()
function sum2(...args) {
    let arg = Array.from(arguments)
    console.log(arg.reduce((sum, cur) => sum + cur))
}
sum2(1,3,4) //8
// 這種方法也能夠用來轉換Set和Map
View Code
3.ES6 展開運算符
function sum(a, b) {
    let args = [...arguments]
    console.log(args.reduce((sum, cur) => sum + cur))
}
sum(1,3) // 4
View Code
4.利用 concat + apply
function sum(a,b) {
    let args = Array.prototype.concat.apply([], arguments)
    console.log(args.reduce((sum, cur) => sum + cur))
}
View Code

5.for ... in 循環數組

function sum (a,b) {
    let args = []
    for(i in arguments) {
        args.push(arguments[i])
    }
    console.log(args.reduce((sum, cur) => sum + cur))
}
sum(1,3) // 4
View Code

6.for ... of 循環app

 function sum (a, b) {
     let args = []
     for( item of arguments) {
        args.push(item)
     }
     console.log(args.reduce((sum, cur) => sum + cur))
 }
View Code
相關文章
相關標籤/搜索