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

JavaScript中如何删除数组内X元素及其之后所有元素并返回前置内容

实现方案

核心逻辑很简单:先找到元素X在数组中首次出现的索引,再截取数组开头到该索引前的片段即可,同时可以兼容数组中不存在X的边界场景。

常用语言实现示例

JavaScript

const originArr = ['A' , 'B' , 'C' , 'D' , 'X' , 'Z' , 'A' , 'B' , 'F'];
const xIndex = originArr.indexOf('X');
const res = xIndex > -1 ? originArr.slice(0, xIndex) : originArr;
// res 输出 ['A','B','C','D']

Python

origin_arr = ['A' , 'B' , 'C' , 'D' , 'X' , 'Z' , 'A' , 'B' , 'F']
try:
    x_index = origin_arr.index('X')
    res = origin_arr[:x_index]
except ValueError:
    # 数组无X时返回原数组
    res = origin_arr
# res 输出 ['A', 'B', 'C', 'D']

Java

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        List<String> originList = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "X", "Z", "A", "B", "F"));
        int xIndex = originList.indexOf("X");
        List<String> res = xIndex > -1 ? originList.subList(0, xIndex) : originList;
        // res 输出 [A, B, C, D]
    }
}

注意事项

  • 如果数组中存在多个X,默认取第一个出现的X的位置做截取,符合示例需求
  • 如果X在数组第一个位置,截取结果为空数组
  • 如果数组中不存在X,上述示例默认返回原数组,可根据实际需求调整为返回空数组等其他逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:36:04