Isaac Lubow
Isaac Lubow

Reputation: 3573

How can I pass an array of strings to a function as arguments?

I have a couple of arrays, like so:

var galImgs = ["http://domain.tld/gallery/image-001.jpg",
               "http://domain.tld/gallery/image-002.jpg",
               "http://domain.tld/gallery/image-003.jpg"],
    preloadImgs = [];

And I'd like to use a simple for loop to load images from the values in the galImgs array, like so:

function preload() {
    for (i = 0; i < preload.arguments.length; i++) {
    preloadImgs[i] = new Image();
    preloadImgs[i].src = preload.arguments[i];
    }
}

However, calling

preload(galImgs);

passes in the array as a single string, instead of comma-separated strings. How can I pass the galImgs array so it will be read as individual arguments?

Upvotes: 2

Views: 9179

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1074158

However, calling

preload(galImgs);

passes in the array as a single string, instead of comma-separated strings.

No, it passes in the array, not a string. You've actually gone to too much trouble in your preload function, just use the array you were given:

function preload(a) {
    for (i = 0; i < a.length; i++) {
        preloadImgs[i] = new Image();
        preloadImgs[i].src = a[i];
    }
}

(And declare the i variable within the function, which I haven't added above; as it is, you're falling prey to The Horror of Implicit Globals.)

This has the advantage of not using the arguments pseudo-array, which is a performance hit on most implementations.

If you want, though, you can use an array to pass discrete arguments to preload, via the apply function:

preload.apply(undefined, galImgs);

The first argument is used for this within the function, you can just use undefined for the default; the second argument is the array, which will show up in the function as discrete arguments.

Upvotes: 5

SaravananArumugam
SaravananArumugam

Reputation: 3720

There's nothing to worry about having viewing it as a single string. Just by providing index to your array, you would be able to get the individual strings.

galImgs[0] would return you the string "http://domain.tld/gallery/image-001.jpg"

You can use gallmgs is an array object and you would have all the accessors of an array in this. Try gallmgs.length.

Upvotes: 0

Amir Raminfar
Amir Raminfar

Reputation: 34149

The problem is your using the arguments keyword to find the passed in event. What you really want is

function preload(images) {
    for (i = 0; i < images.length; i++) {
    preloadImgs[i] = new Image();
    preloadImgs[i].src = images[i];
    }
}

To help you understand better, your old way was fine except one thing..

preload.arguments.length == 1
preload.arguments[0] == galImgs
preload.arguments[0][0] == galImgs[0]

Upvotes: 2

Chris Nielsen
Chris Nielsen

Reputation: 14738

You are looking for the apply method:

preload.apply(null, galImgs);

Should do it!

Upvotes: 1

Related Questions