简体   繁体   English

array.push()引发奇怪的错误

[英]array.push() throws weird error

I'm trying to push elements into array X while iterating through array Y . 我试图在遍历数组Y同时将元素推入数组X At some point, while pushing a new element into array X, I get an "Unexpected token :" error in the browser console. 在某个时候,在将新元素推入数组X时,在浏览器控制台中出现“意外令牌:”错误。 I am able to push several elements properly before it fails (almost every time around 7th element). 我能够在失败之前(几乎每次在第7个元素左右)正确地推送几个元素。

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. 从脚本中可以看到,我试图在HTML中的8个不同位置的元素上随机显示照片。

Seems the problem is in the setTimeout function. 似乎问题出在setTimeout函数中。 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 ). 并尝试对其进行评估(使用eval )。

The problem is that JS consider img_path.jpg as a variable. 问题是JS将img_path.jpg视为变量。

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: 将匿名函数发送给setTimeout:

REALFIX: REALFIX:

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

Don't call setTimeout with a string argument. 不要使用字符串参数调用setTimeout。 Always use a function. 始终使用功能。 Using the string in this case subjects this code to injection attacks if the img variable is vulnerable. 如果img变量易受攻击,则在这种情况下使用字符串会使此代码遭受注入攻击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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