简体   繁体   中英

array.push() throws weird error

I'm trying to push elements into array X while iterating through array Y . At some point, while pushing a new element into array X, I get an "Unexpected token :" error in the browser console. I am able to push several elements properly before it fails (almost every time around 7th element).

It is recursive function, and maybe that causes an issue... Here is the code:

function getPosition(img) {
    var tmpRandPosition = Math.floor(Math.random() * (9));

    if($.inArray(galleryPositions[tmpRandPosition], populatedPositions) != -1) {
        setTimeout("getPosition("+img+")",1);
    } else {
        populatedPositions.push(galleryPositions[tmpRandPosition]);

        return true;
    }
}

As you can see from the script, I'm trying to display photos randomly at 8 different positioned elements in HTML.

Seems the problem is in the setTimeout function. Try to pass the argument to that function using an anonymous function instead of concatenation:

setTimeout(function() { getPosition(img) }, 1);

This will break:

setTimeout("getPosition("+img+")",1);

as it actually writes:

setTimeout("getPosition(img_path.jpg)",1);

and tries to evaluate it (using eval ).

The problem is that JS consider img_path.jpg as a variable.

Fix:

setTimeout("getPosition('"+img+"')",1);

But never do it this way as it's not good or fast to evaluate a string.

Send instead an anonymous function to setTimeout:

REALFIX:

setTimeout(function() {
    getPosition(img);
}, 1);

Don't call setTimeout with a string argument. Always use a function. Using the string in this case subjects this code to injection attacks if the img variable is vulnerable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM