这是我得到的密码。我环顾四周,不太明白。
这是我的问题函数破坏者接受一个参数,一个数组,但是当它被调用时,发送3个参数:一个数组和两个整数。
如果函数中的两个整数参数没有被传递,我如何访问它们?Javascript中有什么东西允许这样做吗?
function destroyer(arr) {
// Remove all the value;
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);发布于 2017-04-05 17:30:06
您可以在函数中使用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)));
https://stackoverflow.com/questions/43237793
复制相似问题