gpt4 book ai didi

JavaScript 参数传递

转载 作者:行者123 更新时间:2023-12-03 04:37:20 27 4
gpt4 key购买 nike

这是我得到的代码。我环顾四周,不太明白。

这是我的问题,函数 destroyer 接受一个参数和一个数组,但是当它被调用时,会发送 3 个参数:一个数组和 2 个整数。

如果函数中的两个整数参数没有被传递,如何访问它们? Javascript 中有什么东西可以允许这样做吗?

         function destroyer(arr) {
// Remove all the value;
return arr;

}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

最佳答案

您可以在函数中使用arguments变量来获取传递参数的列表。

// ES5
function destroyer(arr) {
var pieces = Array.prototype.splice.call(arguments, 1);
var i = 0;

while (arr[i]) {
-1 === pieces.indexOf(arr[i]) ? i++ : arr.splice(i, 1);
}

return arr;
}

// ES6
function destroyer2(arr, ...pieces) {
var i = 0;

while (arr[i]) {
-1 === pieces.indexOf(arr[i]) ? i++ : arr.splice(i, 1);
}

return arr;
}

console.log(JSON.stringify(destroyer([1, 2, 3, 1, 2, 3], 3, 1)));
console.log(JSON.stringify(destroyer2([1, 2, 3, 1, 2, 3], 2, 3)));

关于JavaScript 参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43237793/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com