[js][js array]新增屬性至物件陣列的所有元素中

  • 533
  • 0
  • 2019-02-02
物件陣列.forEach(function(el){
      el.屬性名稱=屬性值;
  });

說明:

其中el是元素的縮寫,其實想改任何名稱都可以

懂得如何使用forEach之後,想新增或刪除屬性也都是可以的.

以下範例將index新增至people物件陣列的所有元素之中

  let people=[
  {name:'person1',age:20},
  {name:'person2',age:21},
  {name:'person3',age:22},
  {name:'person4',age:23},
  {name:'person5',age:24},
  {name:'person6',age:25},
  {name:'person7',age:26},
];

let cnt=1;
addIdx(1,people);

console.log(people);

function addIdx(startIdx,objArr){
    let cnt=startIdx;
    objArr.forEach(function(el){
      el.index=cnt;
      cnt++;
  });
}