小编典典

在javascript中,如何在数组中搜索子字符串匹配项

javascript

我需要在JavaScript中搜索数组。搜索将仅针对字符串的一部分进行匹配,因为该字符串将分配有其他数字。然后,我需要返回带有完整字符串的成功匹配的数组元素。

var windowArray = new Array ("item","thing","id-3-text","class");

我需要搜索其中包含的数组元素,"id-"并且也需要在元素中提取其余文本(即"id-3-text")。

谢谢


阅读 363

收藏
2020-05-01

共1个答案

小编典典

在您的特定情况下,您可以使用一个无聊的旧柜台来做到这一点:

var index, value, result;
for (index = 0; index < windowArray.length; ++index) {
    value = windowArray[index];
    if (value.substring(0, 3) === "id-") {
        // You've found it, the full text is in `value`.
        // So you might grab it and break the loop, although
        // really what you do having found it depends on
        // what you need.
        result = value;
        break;
    }
}

// Use `result` here, it will be `undefined` if not found

但是,如果您的数组是稀疏的,则可以通过适当设计的for..in循环来更有效地执行此操作:

var key, value, result;
for (key in windowArray) {
    if (windowArray.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
        value = windowArray[key];
        if (value.substring(0, 3) === "id-") {
            // You've found it, the full text is in `value`.
            // So you might grab it and break the loop, although
            // really what you do having found it depends on
            // what you need.
            result = value;
            break;
        }
    }
}

// Use `result` here, it will be `undefined` if not found

当心for..in没有hasOwnProperty!isNaN(parseInt(key,10))检查的幼稚的循环。


离题

另一种写法

var windowArray = new Array ("item","thing","id-3-text","class");

var windowArray = ["item","thing","id-3-text","class"];

…这对您来说键入的次数较少,也许(这一点是主观的)更容易阅读。这两个语句的结果完全相同:具有这些内容的新数组。

2020-05-01