0

从下面的代码示例中,我试图在遍历 text_array 的每个用户时从文本中获取位置。从文本中提取位置后,我试图将值放回与正确用户对应的数组中,但它给了我错误“text_array [i] 未定义”。我做错了什么?

function replace_undefined(text_array) {
    var userLocationText = {};
    for (i = 0, l = text_array.length; i < l; i++) {
        console.log(text_array[i].user);
        userLocationText[text_array[i].user] = text_array[i].location;
        var text = text_array[i].text;
        Placemaker.getPlaces(text, function (o) {
            console.log(o);
            if ($.isArray(o.match)) {
                if (o.match[0].place.name == "Europe" || o.match[0].place.name == "United States") {
                    var location = o.match[1].place.name;
                    userLocationText[text_array[i].user] = location;
                }
                if ($.isArray(o.match)) {
                    if (o.match[0].place.name !== "Europe") {
                        var location = o.match[0].place.name;
                        userLocationText[text_array[i].user] = location;
                    }
                }
            } else if (!$.isArray(o.match)) {
                var location = o.match.place.name;
                userLocationText[text_array[i].user] = location;
            }

            console.log(text_array);
        });
    }
}

}

text_array = [{
    user: a,
    user_id: b,
    date: c,
    profile_img: d,
    text: e,
    contentString: f,
    url: g,
    location: undefined
}, {
    user: a,
    user_id: b,
    date: c,
    profile_img: d,
    text: e,
    contentString: f,
    url: g,
    location: undefined
}, {
    user: a,
    user_id: b,
    date: c,
    profile_img: d,
    text: e,
    contentString: f,
    url: g,
    location: undefined
}];
4

1 回答 1

0

如上所述Placemaker.getPlaces肯定是异步的,所以这是一个肮脏的闭包:

Placemaker.getPlaces(text, (function () {
  var z = i;
  return function (o) {
    var i = z;
    ...
    console.log(text_array);
    };
})());

如果您使用除“i”之外的另一个变量,在它自己的回调中提取函数等,它会更干净。

基本上,不是发送一个函数作为 Placemaker.getPlaces 的第二个参数执行,而是将其包装在另一个立即执行的函数中。立即执行的包装函数保存“i”的当前值,并返回初始匿名函数。Placemaker.getPlaces 准备好后将使用初始函数,就像以前一样。

但是现在,由于闭包,我的“z”变量保存了在 for 循环中存在的“i”的值,并且可以在循环结束后很长时间内使用。

我知道,这不是很清楚。

编辑:好吧,也许这个小提琴会有所帮助。

于 2012-08-22T18:32:21.603 回答