JavaScript:如何获取destroyer函数调用初始数组后的参数?
destroyer Function Hey there! Let's break down how to grab those extra values (2 and 3) passed after your initial array in the destroyer function.
First, let's clear up why your previous attempts didn't work:
return arr[6];fails because your initial array[1,2,3,1,2,3]only has indexes from0to5—there's no element at index6, so this returnsundefined.return arr[1][0];doesn't work either becausearr[1]is the number2, not an array. Trying to access[0]on a number will throw an error or returnundefined.
Solution 1: Use ES6 Rest Parameters (Modern Approach)
The cleanest way to capture all arguments after the initial array is with rest parameters. When defining your function, you can use ... to collect the remaining arguments into an array:
function destroyer(arr, ...targetValues) { // targetValues will be [2, 3] exactly what you need! return targetValues; } // Test it out console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); // Output: [2, 3]
This works because ...targetValues grabs every argument after the first one (arr) and puts them into an array called targetValues.
Solution 2: Use the arguments Object (Legacy Approach)
If you need to support older environments that don't have ES6, you can use the built-in arguments object. It's an array-like object that contains all arguments passed to the function. You can convert it to a real array and slice off the first element:
function destroyer(arr) { // Convert arguments to an array, then remove the first element (the initial array) const targetValues = Array.from(arguments).slice(1); return targetValues; } // Test it console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); // Output: [2, 3]
Alternatively, you can use the older slice syntax for array-like objects:
const targetValues = [].slice.call(arguments, 1);
Bonus: If You Want to Remove Those Values from the Initial Array
Just in case your end goal is to filter out 2 and 3 from the original array (since the function is named destroyer), you can combine the above with filter:
function destroyer(arr, ...targetValues) { return arr.filter(item => !targetValues.includes(item)); } console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); // Output: [1, 1]
内容的提问来源于stack exchange,提问作者James Kerrane

