将数组作为函数参数传递

2025-06-07

将数组作为函数参数传递

SamanthaMing.com 的代码小贴士

如果你想将一个数组传递给可变参数函数,可以使用 ES6 的展开方法将该数组转换为参数列表。太棒了,简洁多了,而且没有了旧方法中不必要的 null 值 👏



function sandwich(a, b, c) { 
  console.log(a) // '🍞'
  console.log(b) // '🥬'
  console.log(c) // '🥓'
}

const food = ['🍞', '🥬', '🥓'];

// Old way
sandwich.apply(null, food);

// ✅ ES6 way
sandwich(...food);


Enter fullscreen mode Exit fullscreen mode

Math与函数一起使用

利用函数将数组转换为参数列表的Math功能非常方便。

示例:找出最大的数字

假设您想使用该Math.max()函数查找最大数字。



const largest = Math.max(5, 7, 3, 4);

console.log(largest); // 7


Enter fullscreen mode Exit fullscreen mode

但你很少会传入单个值。更有可能的是,你想找出数组中的最大元素。所以现在的问题是,如何将一个数组传递给一个接受单个参数而不是数组的函数?

这将是可怕的:



const numbers = [5, 7, 3];

// 🤮 Yuck!
Math.max(numbers[0], numbers[1], numbers[2]);

// ❌ And this won't work
Math.max(numbers); // NaN


Enter fullscreen mode Exit fullscreen mode

幸运的是,我们可以使用 ES6 的 Spread 运算符!



const numbers = [5, 7, 3];

// 😍 Much Better!
Math.max(...numbers); // 7


Enter fullscreen mode Exit fullscreen mode

这里所做的spread是获取数组元素并将其扩展或解包为可变函数的参数列表。



const numbers = [5, 7, 3];

console.log(...numbers); // 5 7 3 


Enter fullscreen mode Exit fullscreen mode

spread用非开发术语解释

如果你觉得这个展开的概念仍然令人困惑,也许我可以尝试用俄罗斯套娃来解释。我喜欢把数组想象成俄罗斯套娃。展开的作用是:

  1. 它将嵌套的娃娃解开(展开)成单独的娃娃。
  2. 现在,您已将所有这些单独的娃娃(参数)整齐地放置在展示柜(功能)中。

不确定这个解释是否有帮助?如果有帮助的话,请留言,我会用一些有趣的方式解释编程概念,比如这个😆

将多个数组作为函数参数传递

扩散的另一个超能力是组合阵列。



const one = [1,2,3];
const two = [4,5,6];

const merged = [...one, ...two];
// [ 1, 2, 3, 4, 5, 6 ]


Enter fullscreen mode Exit fullscreen mode

因此,我们可以利用这个超能力将多个数组作为函数参数传递💪



const one = [1,2,3];
const two = [4,5,6];

Math.max(...one, ...two); // 6


Enter fullscreen mode Exit fullscreen mode

对于那些热衷于此的人来说,想知道是否可以传入 3 个数组。好吧,没错!就像劲量兔子一样,它会不停地跑啊跑啊……(这篇文章不是劲量兔子赞助的,哈哈。不过赞助可能会有变化,联系我劲量兔子吧。我想要一些赞助金😂)



const one = [1,2,3];
const two = [4,5,6];
const three = [2,100,2];

Math.max(...one, ...two, ...three); // 100

Enter fullscreen mode Exit fullscreen mode




什么是可变函数?

你可能注意到我使用了“可变函数”这个术语。计算机科学领域的朋友们可能听说过这个术语。但对于像我一样的酷迷来说,它可能不太熟悉。可变函数是指接受无限或可变个参数的函数。而这个Math.max()函数就是可变函数之一。

资源


感谢阅读❤
打个招呼!Instagram | Twitter | Facebook | Medium |博客

文章来源:https://dev.to/samanthaming/passing-arrays-as-function-arguments-4gcm
PREV
JavaScript 中的 String startsWith() 方法
NEXT
JavaScript 中的数字截断