假设我有这个:
var blockedTile = new Array("118", "67", "190", "43", "135", "520");
还有更多的数组元素,但出于可读性考虑,这些元素很少。无论如何,我可以做一个“for”循环,但每次你点击地图时,它会做500个循环……有没有其他方法来查看某个字符串是否在数组中?
假设我有这个:
var blockedTile = new Array("118", "67", "190", "43", "135", "520");
还有更多的数组元素,但出于可读性考虑,这些元素很少。无论如何,我可以做一个“for”循环,但每次你点击地图时,它会做500个循环……有没有其他方法来查看某个字符串是否在数组中?
当前回答
为什么不用array。filter呢?
var array = ['x','y','z'];
array.filter(function(item,index,array){return(item==YOURVAL)}).
只需将其复制到代码中,就可以了:
Array.prototype.inArray = function (searchedVal) {
return this.filter(function(item,index,array){return(item==searchedVal)}).length==true
}
其他回答
您可以尝试下面的代码。检查http://api.jquery.com/jquery.grep/
var blockedTile = new Array("118", "67", "190", "43", "135", "520");
var searchNumber = "11878";
arr = jQuery.grep(blockedTile, function( i ) {
return i === searchNumber;
});
if(arr.length){ console.log('Present'); }else{ console.log('Not Present'); }
检查加勒比海盗。长度大于0表示字符串存在,否则不存在。
为什么不用array。filter呢?
var array = ['x','y','z'];
array.filter(function(item,index,array){return(item==YOURVAL)}).
只需将其复制到代码中,就可以了:
Array.prototype.inArray = function (searchedVal) {
return this.filter(function(item,index,array){return(item==searchedVal)}).length==true
}
Assuming that you're only using the array for lookup, you can use a Set (introduced in ES6), which allows you to find an element in O(1), meaning that lookup is sublinear. With the traditional methods of .includes() and .indexOf(), you still may need to look at all 500 (ie: N) elements in your array if the item specified doesn't exist in the array (or is the last item). This can be inefficient, however, with the help of a Set, you don't need to look at all elements, and instead, instantly check if the element is within your set:
const blockedTile = new集((“118”、“67”、“190”、“43”、“135”、“520”)); 如果(blockedTile.has (" 118 ")) { // 118在你的Set中 console.log(“发现118”); }
如果出于某种原因需要将集合转换回数组,可以通过使用array .from()或扩展语法(…)来实现,但是,这将遍历整个集合的内容(将是O(N))。集合也不会保留重复项,这意味着数组不会包含重复项。
根据可用的JavaScript版本,你可以使用indexOf:
返回数组中给定元素所在的第一个索引,如果不存在则返回-1。
或者一些:
测试数组中的某些元素是否通过了所提供函数实现的测试。
但是,如果你做了这种存在性检查,你会更好地使用一个对象来存储你的字符串(或者一个对象以及数组,这取决于你对你的数据做什么)。
if(array.indexOf("67") != -1) // is in array