要向数组对象中添加键值对,可以使用以下几种方法:
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}]
注意:以上方法都是将键值对添加到数组中的对象元素上,而不是直接将键值对添加到数组中。