JavaScript 数组操作:在数组开头插入新元素
在 JavaScript 中,可以使用 unshift() 方法将一个新的对象插入到数组的第一位。
示例代码:
let busLines = [{lineId: '0001', lineName: '1路', applyNum: 10}, {lineId: '0005', lineName: '5路', applyNum: 10}, {lineId: '0003', lineName: '快1路', applyNum: 10}];
let newLine = {lineId: '0014', lineName: '14路', applyNum: 17};
busLines.unshift(newLine);
console.log(busLines);
运行结果:
[
{lineId: '0014', lineName: '14路', applyNum: 17},
{lineId: '0001', lineName: '1路', applyNum: 10},
{lineId: '0005', lineName: '5路', applyNum: 10},
{lineId: '0003', lineName: '快1路', applyNum: 10}
]
可以看到,新的对象已经成功插入到了数组的第一位。
原文地址: https://www.cveoy.top/t/topic/qhuf 著作权归作者所有。请勿转载和采集!