Ant*_*ony 2 javascript arrays match
我有一个名称数组:
names = ['Jim', 'Jack', 'Fred']
Run Code Online (Sandbox Code Playgroud)
我还从函数中收到了一个值,这是一个字符串形式的名称,例如:
returnedValue = 'Jim'
Run Code Online (Sandbox Code Playgroud)
如何针对names数组的值运行returnedValue字符串并测试匹配?
我的感觉是你想要使用数组原型的.filter方法,但我无法想象如何这样做.
有一个indexOf方法,所有数组都有(旧版本的Internet Explorer除外)将返回数组中元素的索引,如果不在数组中,则为-1:
if (yourArray.indexOf("someString") > -1) {
//In the array!
} else {
//Not in the array
}
Run Code Online (Sandbox Code Playgroud)
如果您需要支持旧的IE浏览器,可以使用MDN文章中的代码使用polyfill this方法.