伪数组转数组的几种方式

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 循环

 function sum (a, b) {
let args = []
for( item of arguments) {
args.push(item)
}
console.log(args.reduce((sum, cur) => sum + cur))
}
View Code

posted @ 2019-11-09 17:18  ichthyo-plu  阅读(...)  评论(...编辑  收藏