【问题标题】:JavaScript: Cut out Array of Strings until a certain String matches (the elegant way)JavaScript:切出字符串数组,直到某个字符串匹配(优雅的方式)
【发布时间】:2021-11-26 14:22:56
【问题描述】:

假设我有以下数组:

const arr = [ '0', 'parentNode', 'children', '0', 'values' ]

我的目标是切割数组,直到某个字符串匹配(所有之后该字符串)。

所以如果我选择 children 作为字符串,结果将是:

const arr = [ '0', 'parentNode', 'children']

我当前的实现有效,我正在创建一个大函数并迭代数组,当条件成立时将每个元素推送到一个新数组......

但我想要一个更优雅的解决方案,也许是 oneliner。

在 Python 中,这是可能的,这在 JavaScript 中会是什么样子?

【问题讨论】:

    标签: javascript arrays reactjs ecmascript-6


    【解决方案1】:

    有很多方法。

    indexoffindIndex如果你需要使用回调,因为比较更复杂)和slice

    const index = arr.indexOf(target);
    const result = index < 0 ? [] : arr.slice(index);
    

    一个简单的循环:

    const result = [];
    let found = false;
    for (const element of arr) {
        found = found || element === target;
        if (found) {
            result.push(element);
        }
    }
    

    filter:

    let found = false;
    const result = arr.filter(element => {
        found = found || element === target;
        return found;
    });
    

    【讨论】:

      【解决方案2】:

      这是单线解决方案:

      arr.slice(0, arr.indexOf('children') + 1)

      它表现良好,因为使用了本机代码(V8、SpiderMonkey 等)。但不处理错误。如果没有找到'children',您将收到空数组。

      【讨论】:

        猜你喜欢
        • 2011-04-25
        • 2013-09-06
        • 1970-01-01
        • 2020-03-27
        • 1970-01-01
        • 2015-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多