我怎样才能在代码中使用闭包?

时间:2015-12-29 12:24:45

标签: javascript closures

我有这样的JSON:

[
   {"data":"a"},
   {"data":"b"},
   {"data":"c"}
]

使用JavaScript,我想添加一个增量id字段:

[
   {"data":"a","id":"xx_1"},
   {"data":"b","id":"xx_2"},
   {"data":"c","id":"xx_3"}
]

但我想利用JavaScript闭包

var cnt

在我的下面的代码中我该怎么做?

var data=[
    {"data":"a"},
    {"data":"b"},
    {"data":"c"}
    ];
    var cnt=0;
    data.map(function(data){
       data.id="xx_"+cnt;
       cnt++;
    })

console.log(data);

3 个答案:

答案 0 :(得分:3)

.map回调中,第二个参数为index,因此您可以使用它并且不使用不必要的变量cnt,就像这样



var data = [
  {"data":"a"},
  {"data":"b"},
  {"data":"c"}
];

data = data.map(function (element, index) {
  element.id = 'xx_' + (index + 1);
  return element;
});

console.log(data);




答案 1 :(得分:1)

无需使用.map,因为您只修改了数组中的对象。使用.forEach((value, index) => {})

var data = [
  {"data":"a"},
  {"data":"b"},
  {"data":"c"}
];

data.forEach(function(obj, index) {
    obj.id = 'xx_' + (index + 1);
});

答案 2 :(得分:0)

检查此fiddle

var data=[
        {"data":"a"},
        {"data":"b"},
        {"data":"c"}
];
var counter = (function () { //this is a closure that will return an incremented count value everytime it is called
  var count = 1; // you can initialize to a different value if you want
  return function () {return count += 1;}
})();
data.map(function(data){
  data.id="xx_"+counter(); //calling the counter method
});
console.log(data);