JS中for in语句错误的主体

body of a for in statement error in JS

我正在为此绞尽脑汁,我已经阅读了之前所有已回答的问题,但我觉得我只是错过了一些东西。

JSHint 给出错误:

The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.

你们会如何解决这个错误?

function checkCollision(X, Y, arrayObjs) {
for (var obj in arrayObjs) {

 var objX = (arrayObjs[obj].x / 101).toFixed(0);
    var objY = (arrayObjs[obj].y / 83).toFixed(0);




    //checking collision by checking character placement as well as enemies

    if ((objX == (X / 101).toFixed(0)) && (objY == (Y / 83).toFixed(0))) {
        //collision
        return true;
    }
}

return false; }

不要使用 for in 循环,而是使用普通的 for 循环,这样你就可以在不遍历原型的情况下迭代数组:

function checkCollision(X, Y, arrayObjs) {
    for (var i = 0, length = arrayObjs.length; i < length; i++) {
        var objX = (arrayObjs[i].x / 101).toFixed(0);
        var objY = (arrayObjs[i].y / 83).toFixed(0);
        //checking collision by checking character placement as well as enemies

        if ((objX == (X / 101).toFixed(0)) && (objY == (Y / 83).toFixed(0))) {
            //collision
            return true;
        }
    }
    return false;
}

有关详细信息,请参阅以下 Stack Overflow post:What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?