You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript:如何获取destroyer函数调用初始数组后的参数?

How to Get Arguments After the Initial Array in the 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 from 0 to 5—there's no element at index 6, so this returns undefined.
  • return arr[1][0]; doesn't work either because arr[1] is the number 2, not an array. Trying to access [0] on a number will throw an error or return undefined.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:15:14