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

reu*_*b77 50 javascript arrays search

我需要在javascript中搜索数组.搜索将仅匹配要匹配的字符串的一部分,因为字符串将分配给它的附加编号.然后我需要使用完整的字符串返回成功匹配的数组元素.

var windowArray = new Array ("item","thing","id-3-text","class");
Run Code Online (Sandbox Code Playgroud)

我需要在其中搜索数组元素,"id-"我还需要拉动元素中的其余文本(即."id-3-text").

谢谢

nic*_*ckb 38

If you're able to use Underscore.js in your project, the _.filter() array function makes this a snap:

// find all strings in array containing 'thi'
var matches = _.filter(
    [ 'item 1', 'thing', 'id-3-text', 'class' ],
    function( s ) { return s.indexOf( 'thi' ) !== -1; }
);
Run Code Online (Sandbox Code Playgroud)

The iterator function can do whatever you want as long as it returns true for matches. Works great.

Update 2017-12-03:
This is a pretty outdated answer now. Maybe not the most performant option in a large batch, but it can be written a lot more tersely and use native ES6 Array/String methods like .filter() and .includes() now:

// find all strings in array containing 'thi'
const items = ['item 1', 'thing', 'id-3-text', 'class'];
const matches = items.filter(s => s.includes('thi'));
Run Code Online (Sandbox Code Playgroud)

Note: There's no <= IE11 support for String.prototype.includes() (Edge works, mind you), but you're fine with a polyfill, or just fall back to indexOf().


smn*_*h90 30

从给定数组中获取子字符串数组的最简单方法是使用 filter 并包括:

myArray.filter(element => element.includes("substring"));
Run Code Online (Sandbox Code Playgroud)

上面的将返回一个子字符串数组。

myArray.find(element => element.includes("substring"));
Run Code Online (Sandbox Code Playgroud)

上面的将返回数组中的第一个结果元素。

myArray.findIndex(element => element.includes("substring"));
Run Code Online (Sandbox Code Playgroud)

上面的将返回数组中第一个结果元素的索引。


小智 27

这里的人使这种方式变得太困难了。只需执行以下操作...

myArray.findIndex(element => element.includes("substring"))
Run Code Online (Sandbox Code Playgroud)

findIndex()是ES6的高阶方法,它遍历数组的元素并返回与某些条件匹配(作为函数提供)的第一个元素的索引。在这种情况下,我使用ES6语法来声明高阶函数。element是函数的参数(可以是任何名称),粗箭头声明以下内容为匿名函数(除非占用多个行,否则不需要用大括号括起来)。

在其中,findIndex()我使用了非常简单的includes()方法来检查当前元素是否包含所需的子字符串。

  • 令人惊奇的答案,正是我一直在寻找的。谢谢你! (2认同)

T.J*_*der 14

在您的具体情况下,您只需使用无聊的旧计数器即可:

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
Run Code Online (Sandbox Code Playgroud)

但是如果你的数组稀疏,你可以使用设计合理的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
Run Code Online (Sandbox Code Playgroud)

注意for..in没有hasOwnProperty!isNaN(parseInt(key, 10))检查的天真循环; 这就是原因.


偏离主题:

另一种写作方式

var windowArray = new Array ("item","thing","id-3-text","class");
Run Code Online (Sandbox Code Playgroud)

var windowArray = ["item","thing","id-3-text","class"];
Run Code Online (Sandbox Code Playgroud)

...这对你来说打字较少,也许(这一点是主观的)更容易阅读.这两个语句具有完全相同的结果:包含这些内容的新数组.


Jon*_*eJS 12

只需搜索普通旧字符串即可 indexOf

arr.forEach(function(a){if (typeof(a) == 'string' && a.indexOf('curl')>-1) console.log(a);})
Run Code Online (Sandbox Code Playgroud)


Kar*_*hik 5

实现这一目标的最简单的香草 javascript 代码是

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

//if you only want to match id- as prefix 
var matches = windowArray.filter(function(windowValue){
  if(windowValue) {
      return (windowValue.substring(0, textToFind.length) === textToFind);
  }
}); //["id-3-text"]

//if you want to match id- string exists at any position
var matches = windowArray.filter(function(windowValue){
  if(windowValue) {
      return windowValue.indexOf(textToFind) >= 0;
  }
}); //["id-3-text", "3-id-text"]
Run Code Online (Sandbox Code Playgroud)