【问题标题】:passing the parameters as an array将参数作为数组传递
【发布时间】:2014-04-25 10:10:32
【问题描述】:

我使用了 preload() 方法:

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

效果很好。但是现在我想将所有参数放在一个数组中,所以现在应该是这样的:

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

preload(myArray)

但显然这是错误的方法,因为预加载是加载以逗号分隔的参数而不是组合所有参数的数组。

所以,我很想知道有什么事情要做吗?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以使用preload.apply(可以从Function 对象的Function.prototype.apply 获得应用),它可以将一组数据作为参数展开,就像这样

    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 特殊对象。

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

    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 ]
    

    【讨论】:

      猜你喜欢
      • 2011-08-12
      • 2016-09-26
      • 2021-06-03
      • 2014-03-09
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多