es6语法如何利用arguments转换成数组

2025年03月05日 建站教程

arguments是一个类似数组的对象, 对应于传递给函数的参数。下面web建站小编带大家了解一下利用arguments转换成数组。

1、for遍历

function text(){
  let newArray = [];
  for (let i = 0; i < arguments.length; i++) {
	newArray.push(arguments[i]);
  }
  return newArray;
}
console.log(text(1, 2, 3, 4, 5, 6, 7, 8));
//(8) [1, 2, 3, 4, 5, 6, 7, 8]

2、Array.prototype.slice将arguments转成array

function text(){
  let newArray = Array.prototype.slice.call(arguments);
  return newArray;
}
console.log(text(1, 2, 3, 4, 5, 6, 7, 8));
//(8) [1, 2, 3, 4, 5, 6, 7, 8]

3、ES6语法 Array.From

function text(){
return Array.from(arguments);
}
console.log(text(1, 2, 3, 4, 5, 6, 7, 8));
//(8) [1, 2, 3, 4, 5, 6, 7, 8]

4、剩余参数

function text(){
return [...arguments];
}
console.log(text(1, 2, 3, 4, 5, 6, 7, 8));
//(8) [1, 2, 3, 4, 5, 6, 7, 8]

本文链接:http://so.lmcjl.com/news/24347/

展开阅读全文
相关内容