在JavaScript中,你如何寻找一个数组的字符串匹配 [英] In javascript, how do you search an array for a substring match

查看:115
本文介绍了在JavaScript中,你如何寻找一个数组的字符串匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要寻找在JavaScript的数组。搜索将是唯一的字符串相匹配的字符串将分配给它addtional号码的一部分。然后,我需要与完整的字符串返回成功匹配的数组元素。

I need to search an array in javascript. The search would be for only part of the string to match as the string would have addtional numbers assigned to it. I would then need to return the successfully matched array element with the full string.

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

我要搜索的数组元素与ID - 在这一点,我需要拉元素中的文本的其余部分以及(即ID-3-文)。

I need to search for the array element with "id-" in it and i need to pull the rest of the text in the element as well (ie. "id-3-text").

感谢

推荐答案

在特定的情况下,你可以只是一个无聊的老计数器做到这一点:

In your specific case, you can do it just with a boring old counter:

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函数(键,10))检查; 这里的原因

题外话

另一种方式来写

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

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

...这是你少打字,也许(这一点是主观的)多一点轻松阅读。这两个语句具有完全相同的结果:与内容的新数组

...which is less typing for you, and perhaps (this bit is subjective) a bit more easily read. The two statements have exactly the same result: A new array with those contents.

这篇关于在JavaScript中,你如何寻找一个数组的字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆