如何检查给定字符串是否已存在于JavaScript中的数组或列表中? [英] How to check whether a given string is already present in an array or list in JavaScript?
本文介绍了如何检查给定字符串是否已存在于JavaScript中的数组或列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
Javascript - array.contains(obj)
在JavaScript数组中查找项目的最佳方法?
我想检查一下列表或地图中的the这个词。是否有任何类型的内置函数?
I want to check, for example, for the word "the" in a list or map. Is there is any kind of built in function for this?
推荐答案
在javascript中你有数组(列表)和对象(地图) 。
In javascript you have Arrays (lists) and Objects (maps).
它们的文字版本如下所示:
The literal versions of them look like this:
var mylist = [1,2,3]; // array
var mymap = { car: 'porche', hp: 300, seats: 2 }; // object
如果您想知道数组中是否存在值,只需循环遍历它:
if you which to figure out if a value exists in an array, just loop over it:
for(var i=0,len=mylist.length;i<len;i++) {
if(mylist[i] == 2) {
//2 exists
break;
}
}
如果要确定地图是否有某个密钥或者如果它有一个具有特定值的密钥,您所要做的就是这样访问:
if you which to figure out if a map has a certain key or if it has a key with a certain value, all you have to do is access it like so:
if(mymap.seats !== undefined) {
//the key 'seats' exists in the object
}
if(mymap.seats == 2) {
//the key 'seats' exists in the object and has the value 2
}
这篇关于如何检查给定字符串是否已存在于JavaScript中的数组或列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文