JavaScript数组插入元素:将'14路'插入到数组开头
将'14路'插入到数组的第一位内容:
const originalArray = [{lineId: '0001', lineName: '1路', applyNum: 10}, {lineId: '0005', lineName: '5路', applyNum: 10}, {lineId: '0003', lineName: '快1路', applyNum: 10}];
const newElement = {lineId: '0014', lineName: '14路', applyNum: 17};
const updatedArray = [newElement, ...originalArray];
console.log(updatedArray);
// 输出:[{lineId: '0014', lineName: '14路', applyNum: 17}, {lineId: '0001', lineName: '1路', applyNum: 10}, {lineId: '0005', lineName: '5路', applyNum: 10}, {lineId: '0003', lineName: '快1路', applyNum: 10}]
代码解释:
originalArray是我们初始的数组。newElement是我们要插入的新元素。- 使用
[newElement, ...originalArray]创建了一个新的数组updatedArray,将newElement放置在数组的第一个位置,然后使用...originalArray将originalArray中剩余的元素展开并添加到updatedArray的后面。 - 最后使用
console.log(updatedArray)打印出更新后的数组。
这样就完成了将'14路'插入到数组的第一位操作。
原文地址: https://www.cveoy.top/t/topic/qhuc 著作权归作者所有。请勿转载和采集!