向我的对象数组添加新字段

时间:2017-06-01 18:16:48

标签: javascript arrays json

我有一个很好的 hotdealArray 对象:

   [
        {
            "_id": "5908906b53075425aea0b16d",
            "property": "ATL-D406",
            "discount": 10,
            "hot": true
        },
        {
            "_id": "5908906b53075425aea0b16f",
            "property": "WAT-806",
            "discount": 20,
            "hot": true
        },
        {
            "_id": "5908906b53075425aea0b171",
            "property": "ANA-C202",
            "discount": 30,
            "hot": true
        }
    ]

我试试这个

hotdealArray[i].priceNight = result.res.priceNight;

哪个给出错误:无法设置未定义的属性'priceNight'

如何向 hotdealArray 添加新字段?

这是我要求的for循环:

    for (var i=0; i<hotdealArray.length; i++) {
        var priceNight = 0;
        priceController.getPrice (
            { "body": { "propertyID": hotdealArray[i].property } }, 
            function(result) {
                if (result.error == true) {
                    throw new Error(result.err);
                } 
                priceNight = result.res.priceNight;
                console.log ("priceNight inside: " + priceNight);
            }
        );
        console.log ("priceNight outside: " + priceNight);
        hotdealArray[i].priceNight = priceNight;
    };

在控制台日志中,它只显示:

priceNight inside: 2160
priceNight inside: 2250
priceNight inside: 4455
priceNight inside: 1485

1 个答案:

答案 0 :(得分:1)

还有其他方法,但避免范围问题的一种方法是将内部回调包装在明确定义该范围内i的IIFE中。

        function(result) {
            if (result.error == true) {
                throw new Error(result.err);
            } 
            console.log ("priceNight: " + result.res.priceNight);
            hotdealArray[i].priceNight = result.res.priceNight;
        }

变为

(function (i) {
  return function(result) {
    if (result.error == true) {
      throw new Error(result.err);
    } 
    console.log ("priceNight: " + result.res.priceNight);
    hotdealArray[i].priceNight = result.res.priceNight;
  };
})(i);