将参数作为数组传递 [英] passing the parameters as an array

查看:131
本文介绍了将参数作为数组传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了preload()方法:

I've used a preload() method:

preload('img-1','img-2',...,'img-num')

哪个工作正常。但是现在我想将所有参数放在一个数组中,所以现在就这样:

Which works fine. But now I wanted to place all that parameters in an array, so which would go like this now:

var myArray = ['img-1','img-2',...,'img-num'];

preload(myArray)

但显然这是错误的方法,因为preload是加载由comman分隔的参数而不是组合所有参数的数组。

But obviously this is wrong method as preload is to load the parameters separated by comman not the array which combine all parameters.

所以,我非常好奇知道是否有事要做?

So, I'm very much curious to know if there is something to do?

推荐答案

您可以使用 preload.apply (可从<$ c获取申请$ c> Function object's, Function.prototype.apply ),可以将数据数据作为参数展开,例如

You can use preload.apply (apply is available from the Function object's, Function.prototype.apply), which can spread out an array of data as arguments, like this

preload.apply(this, myArray);

例如,

function printer(first, second, third) {
    console.log(first, second, third);
}

printer(1, 2, 3);
# 1 2 3
printer([1, 2, 3]);
# [1, 2, 3] undefined undefined
printer.apply(this, [1, 2, 3]);
# 1 2 3

由于参数数量可能不同,人们通常会使用 arguments 特殊对象。

Since the number of arguments can vary, people normally use arguments special object.

您可以在函数中获取作为数组的参数列表,如下所示

You can get the list of arguments as an array, within the function, like this

function printer() {
    console.log(Array.prototype.slice.call(arguments));
}

printer(1, 2, 3);
# [ 1, 2, 3 ]
printer([1, 2, 3]);
# [ [ 1, 2, 3 ] ]
printer.apply(this, [1, 2, 3]);
# [ 1, 2, 3 ]

这篇关于将参数作为数组传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆