栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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"];

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517997.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号