将数组中的所有值传递给函数作为参数

编程入门 行业动态 更新时间:2024-10-27 15:20:13
本文介绍了将数组中的所有值传递给函数作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个值数组:

['a','b','c','d' ]

我需要将这些参数作为参数传递给函数:

window.myFunction('a','b','c','d');

如果我只能将数组/对象传入函数,这会更容易,但函数由其他人编写或已经存在,我不能改变它们 - 它们需要作为单独的参数传递,这就是我需要解决的。

传递的值的数量不一致。它可能是一个,它可能是100.

同样,我不能影响功能。他们是怎么样的,我总是会收到一系列的价值观传入他们。

使用 函数对象的 .apply 方法。

window.myFunction。 apply(window,['a','b','c','d']);

.apply 方法调用函数you你可以设置函数的这个值(第一个参数),并且可以使用Array(第二个参数)设置它的参数。

所以我们在这里保存 window 作为 this 的值,我们传递数组作为单独的参数。 Array成员将被分发,就像它们作为单独的参数传递一样,所以就好像你已经做了这样的事情:

窗口。 myFunction的( 'A', 'b', 'C', 'd');

I have an array of values:

['a', 'b', 'c', 'd']

and I need to pass these as parameters to a function:

window.myFunction('a', 'b', 'c', 'd');

This would be easier if I could just pass the array/object into the function, but the functions are written by other people or already exist and I cannot change them - they need to be passed as individual parameters, which is what I need solved.

The number of values being passed is not consistent. It may be one, it may be 100.

Again, I cannot affect the functions. They are how they are, and I will always receive an array of values to pass into them.

解决方案

Use the .apply method of the Function object.

window.myFunction.apply(window, ['a','b','c','d']);

The .apply method invokes the function you're calling, but lets you set the function's this value (the first argument) and lets you set its arguments using an Array (the second argument).

So here we kept window as the this value, and we're passing the Array as the individual arguments. The Array members will be distributed as though they were passed as individual arguments, so it's as if you had done this:

window.myFunction('a','b','c','d');

更多推荐

将数组中的所有值传递给函数作为参数

本文发布于:2023-07-22 03:07:04,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   组中   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!