gpt4 book ai didi

javascript - 将未知数量的参数传递给 JavaScript 函数

转载 作者:IT王子 更新时间:2023-10-29 02:51:07 27 4
gpt4 key购买 nike

有没有办法传递未知数量的参数,例如:

var print_names = function(names) {
foreach(name in names) console.log(name); // something like this
}

print_names('foo', 'bar', 'baz');

另外,如何获取传入的参数个数?

最佳答案

ES3(或 ES5 或老式 JavaScript)

您可以通过神奇的 arguments 对象访问传递给任何 JavaScript 函数的参数,其行为类似于数组。使用 arguments 你的函数看起来像:

var print_names = function() {
for (var i=0; i<arguments.length; i++) console.log(arguments[i]);
}

重要的是要注意 arguments 不是数组。 MDC 有一些很好的文档:https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object

如果你想把 arguments 变成一个数组,这样你就可以做 .slice(), .push() 等,使用这样的东西:

var args = Array.prototype.slice.call(arguments);

ES6/ typescript

有更好的方法!新rest parameters功能有你的支持:

var print_names = function(...names) {
for (let i=0; i<names.length; i++) console.log(names[i]);
}

关于javascript - 将未知数量的参数传递给 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4116608/

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