我希望往一个空数组里面加入另一个数组中的每一个对象的ID
可以使用数组的push方法和map方法来实现:
const arr1 = []; // 空数组
const arr2 = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
]; // 另一个数组
arr2.map(item => arr1.push(item.id)); // 将arr2中每个对象的id加入arr1中
console.log(arr1); // [1, 2, 3]
上述代码中,map方法遍历arr2中的每个对象,并将它们的id加入arr1中。最后输出arr1的结果为[1, 2, 3]。
原文地址: https://www.cveoy.top/t/topic/doj7 著作权归作者所有。请勿转载和采集!