jQuery / JS:一行上的数组引用很好,TypeError:变量未定义下一行

时间:2015-02-23 17:57:32

标签: jquery arrays typeerror

我不明白为什么我继续在console.log行上获取错误TypeError: selected_tiles[count] is undefined(以及我之后尝试使用它的任何时候),当它在之前的if语句中正常工作时。

 //fyi, tiles are divs
var selected_tiles = $("[id^=choice-]");
   //remove deleted buttons (nested divs) from selected_tiles array
for(var count = 0; count<selected_tiles.length; count++){
  if (selected_tiles[count]['id'].substr((selected_tiles[count]['id'].length)-4, selected_tiles[count]['id'].length) == '-del'){
    selected_tiles.splice(count, 1);
  }
  console.log(selected_tiles[count]['id']);
 //was going to put an if statement here to remove the array elements with unselected in their attributes (a data html tag)
}

1 个答案:

答案 0 :(得分:0)

(在答案的最后是一个代替整个循环的单行。)

因为您有时会删除selected_tiles中的条目,所以如果您删除最后条目,selected_tiles[count]将超出数组的结尾 jQuery设置,为您提供undefined,但您无法访问['id']上的undefined

//fyi, tiles are divs
var selected_tiles = $("[id^=choice-]");
//remove deleted buttons (nested divs) from selected_tiles array
for (var count = 0; count < selected_tiles.length; count++) {
    if (selected_tiles[count]['id'].substr((selected_tiles[count]['id'].length) - 4, selected_tiles[count]['id'].length) == '-del') {
        selected_tiles.splice(count, 1);       // <== Deletes an entry
    }
    console.log(selected_tiles[count]['id']);  // <== Assumes count is still valid
    //was going to put an if statement here to remove the array elements with unselected in their attributes (a data html tag)
}

如果删除该条目,请在删除后尝试访问该条目;也许使用else

//fyi, tiles are divs
var selected_tiles = $("[id^=choice-]");
//remove deleted buttons (nested divs) from selected_tiles array
for (var count = 0; count < selected_tiles.length; count++) {
    if (selected_tiles[count]['id'].substr((selected_tiles[count]['id'].length) - 4, selected_tiles[count]['id'].length) == '-del') {
        selected_tiles.splice(count, 1);
    } else {                                   // <== else
        console.log(selected_tiles[count]['id']);
    }
}

旁注:重复查找对象上的相同属性通常是个不好的想法,因为该代码正在selected_tiles[count]selected_tiles[count]['id']上进行。相反,使用变量:

var id;
//fyi, tiles are divs
var selected_tiles = $("[id^=choice-]");
//remove deleted buttons (nested divs) from selected_tiles array
for (var count = 0; count < selected_tiles.length; count++) {
    tile = selected_tiles[count]['id']; // or `selected_tiles[count].id`, of course
    if (id.substr(id.length - 4, id.length) == '-del') {
        selected_tiles.splice(count, 1);
    } else {
        console.log(id);
    }
}

附注2:您正在使用jQuery的未记录的功能。 jQuery对象未记录为具有splice函数。它们有一个,供内部使用,但它没有记录,这意味着它可能在一个点发布和下一个点之间消失。

在这种情况下,您可以考虑改为使用filter

var selected_tiles = $("[id^=choice-]").filter(function(index, entry) {
    if (this.id.substr(id.length - 4, this.id.length) == '-del') {
        return false;
    }
    console.log(this.id);
});

或只是:not

var selected_tiles = $("[id^=choice-]:not([id$=-del])");