要向數(shù)組對象中添加鍵值對,可以使用以下幾種方法:
var arr = [{name: 'Alice'}, {name: 'Bob'}];
arr[0].age = 25;
arr[1].age = 30;
console.log(arr); // [{name: 'Alice', age: 25}, {name: 'Bob', age: 30}]
var arr = [{name: 'Alice'}, {name: 'Bob'}];
arr[0]['age'] = 25;
arr[1]['age'] = 30;
console.log(arr); // [{name: 'Alice', age: 25}, {name: 'Bob', age: 30}]
var arr = [{name: 'Alice'}, {name: 'Bob'}];
Object.assign(arr[0], {age: 25});
Object.assign(arr[1], {age: 30});
console.log(arr); // [{name: 'Alice', age: 25}, {name: 'Bob', age: 30}]
注意:以上方法都是將鍵值對添加到數(shù)組中的對象元素上,而不是直接將鍵值對添加到數(shù)組中。