将值放回数组中相应的用户

put values back to corresponding users in array

本文关键字:用户 数组      更新时间:2023-09-26

在下面的代码示例中,我试图从文本中获取位置,同时循环遍历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
}];

因为Placemaker.getPlaces肯定是异步的,所以这里有一个肮脏的闭包:

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

如果你使用另一个var而不是"i",在它自己的回调中提取函数,那么它会更干净。

基本上,这不会将一个函数作为Placemaker.getPlaces的第二个参数来执行,而是将其封装在另一个立即执行的函数中。立即执行的包装函数保存"i"的当前值,并返回初始匿名函数。初始函数将由Placemaker.getPlaces在其准备就绪时使用,与以前一样。

但现在,由于闭包的原因,我的"z"var保持了在for循环期间存在的"i"的值,并且可以在循环结束后很长一段时间使用。

我知道,不是那么清楚。

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