将'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}]

代码解释:

  1. originalArray 是我们初始的数组。
  2. newElement 是我们要插入的新元素。
  3. 使用 [newElement, ...originalArray] 创建了一个新的数组 updatedArray,将 newElement 放置在数组的第一个位置,然后使用 ...originalArrayoriginalArray 中剩余的元素展开并添加到 updatedArray 的后面。
  4. 最后使用 console.log(updatedArray) 打印出更新后的数组。

这样就完成了将'14路'插入到数组的第一位操作。

JavaScript数组插入元素:将'14路'插入到数组开头

原文地址: https://www.cveoy.top/t/topic/qhuc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录