在 node.js 中的数组中查找字符串的最佳方法是什么?

what is the best way to find string inside array in node.js?

我有一个 node.js 脚本,我想在其中查找给定字符串是否包含在数组中。 我该怎么做?

谢谢。

如果我没理解错的话,您是在数组中查找字符串。

一个简单的方法是使用 indexOf() 函数,它会为您提供找到字符串的索引,或者在找不到字符串时为 returns -1。

示例:

var arr = ['example','foo','bar'];
var str = 'foo';
arr.indexOf(str); //returns 1, because arr[1] == 'foo'

str = 'whatever';
arr.indexOf(str); // returns -1 

编辑 2017 年 10 月 19 日

ES6 的引入给了我们: arr.includes('str') //true/false

在 NodeJS 中,如果您希望匹配字符串数组中的部分字符串,您可以尝试这种方法:

const strings = ['dogcat', 'catfish']
const matchOn = 'dog'

let matches = strings.filter(s => s.includes(matchOn))

console.log(matches) // ['dogcat']

编辑: 根据要求 如何在上下文中使用 fiddle 提供:

var fs = require('fs');                                           
var location = process.cwd();                                     


var files = getFiles('c:/Program Files/nodejs');                                 
var matches = searchStringInArray('c:/Program Files/nodejs/node_modules/npm/bin', files);


console.log(matches);                                             

function getFiles (dir, files_){                                  
    var str = process.argv[2];                                    
    files_ = files_ || [];                                        
    var files = fs.readdirSync(dir);                              
    for (var i in files){                                         
        var name = dir + '/' + files[i];                          
        if (fs.statSync(name).isDirectory()){                     
            getFiles(name, files_);                               
        } else {                                                  
            files_.push(name);                                    
        }                                                         
    }                                                             

    return files_;                                                
}                                                                 

function searchStringInArray (find, files_) {                     
    return files_.filter(s => s.includes(find))                   

}                                                                 

另一种方法是使用some

players = [];

const found = this.players.some(player => player === playerAddress);

if (found) {
    // action
} else {
    // action
}