You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JavaScript数组首元素移至首个0值位置并保持数组长度

解决方法

要实现你需要的数组变换,可以通过数组的splice方法完成元素的删除与插入,确保数组长度不变。针对你的示例场景,代码实现如下:

// 示例数组
let arr = [4,1,2,7,10,0,0,0];

// 定位第一个值为0的元素索引
const firstZeroIndex = arr.indexOf(0);

// 仅在数组存在0时执行操作
if (firstZeroIndex !== -1) {
  // 取出第一个元素和第一个0
  const firstElement = arr[0];
  const firstZero = arr[firstZeroIndex];

  // 删除原数组中的第一个元素和第一个0
  arr.splice(firstZeroIndex, 1);
  arr.splice(0, 1);

  // 将第一个0放到数组开头
  arr.unshift(firstZero);

  // 将原第一个元素插入到1、2之后的位置
  arr.splice(2, 0, firstElement);
}

console.log(arr); // 输出: [0, 1, 2, 4, 7, 10, 0, 0]

代码说明:

  • indexOf(0)快速找到第一个0的位置,作为操作的锚点。
  • splice方法用于删除指定位置的元素,这里分别删除第一个元素和第一个0,为后续插入操作预留位置,保证数组长度不变。
  • unshift将第一个0移到数组最前面,匹配示例的开头要求。
  • 最后用splice在索引2的位置插入原第一个元素,调整到示例期望的元素顺序。

如果需要严格按照“将第一个元素移动到第一个0的位置”的需求实现(即原第一个0的位置替换为第一个元素,原第一个元素位置替换为0),可以使用以下通用版本:

let arr = [4,1,2,7,10,0,0,0];
const firstZeroIndex = arr.indexOf(0);

if (firstZeroIndex !== -1) {
  // 交换第一个元素和第一个0的位置
  [arr[0], arr[firstZeroIndex]] = [arr[firstZeroIndex], arr[0]];
}

console.log(arr); // 输出: [0, 1, 2, 7, 10, 4, 0, 0]

内容的提问来源于stack exchange,提问作者Flash20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:45:19