([numbers],数字)作为函数参数,如何从[]之外获取数字

([ numbers ], numbers) as function parameter, how to get numbers from outside of [ ]?

本文关键字:数字 获取 numbers 函数 参数      更新时间:2023-09-26
function a(b) {
 var array = Array.prototype.slice.call(b);
 console.log(array);
 var array_two = ???;
 console.log(array_two);
}
a([1, 2, 3], 1, 2);

console.log(array);给出了预期的输出[1, 2, 3]

我想在这里实现的是获得[1, 2] -数字后[],加入为数组。我想b[number]会解决这个问题。b[0] -数组,b[1] -数组后的第一个数字,b[2] -数组后的第二个数字,但显然不是这样工作的。你知道有什么解决办法吗?

您可以在a函数中使用Rest parameter,其中...c被设置为a函数的最后一个参数,并且可以在a函数体中作为标识符为c的数组访问。参见ECMAScript文档中的SpreadElement是什么?它和MDN的Spread算子一样吗?

function a(b, ...c) {
 var array = Array.prototype.slice.call(b);
 console.log(array, c);
}
console.log(
  a([1, 2, 3], 1, 2)
  , a([1,2,3], "a", "b", "c", "d", "e", "f", "g")
);

您可以将函数更改为

function a(array,firstArgAfterArray,secondArgAfterArray)

或者你可以在数组后面获取第一个和第二个参数,就像

arguments[1] , arguments[2]

您可以使用预定义变量参数实现所有给定参数的数组。但是在这种情况下,你必须删除第一个元素(因为它是array_one):

var array_two = Array.prototype.slice.call(arguments, 1);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments