[英]How can i search for an element without using any loops in javascript
I have an array like [1,2,3,4,5,6,7] how can I search for an element without using any loops and built-in methods in javascript
? 我有一个类似[1,2,3,4,5,6,7]的数组,如何在不使用
javascript
使用任何循环和内置方法的情况下搜索元素?
Thanks in advance 提前致谢
You could use a recursive approach and rest parameters ...
for the array, without using some array methods. 您可以使用递归方法并为数组使用rest参数
...
,而无需使用某些数组方法。
function find(search, array) { return function check(search, value, ...rest) { return search === value || rest.length && check(search, ... rest) || false; }(search, ...array); } console.log(find(1, [1, 2, 3, 4, 5, 6, 7])); console.log(find(42, [1, 2, 3, 4, 5, 6, 7]));
You can use indexOf method to search for element. 您可以使用indexOf方法搜索元素。 I hope this will help you.
我希望这能帮到您。
var array = [1,2,3,4,5,6,7]; var searchElement = 5; if(array.indexOf(searchElement)>-1) { console.log('element present in array'); } else { console.log('element not present in array'); }
If you don't want to search all the elements. 如果您不想搜索所有元素。 First iterate through all the elements and construct a object.
首先遍历所有元素并构造一个对象。 The construction of object is one time process and use this object for searching an element.
对象的构建是一个一次性的过程,并使用该对象搜索元素。
var array = [1,2,3,4,5,6,7]; var obj = {}; for(var i=0;i<array.length;i++) { if(obj.hasOwnProperty(array[i])) continue; obj[array[i]] = true; } var searchElement = 7; if(obj[searchElement] == true) { console.log("element present"); } else { console.log("element not present"); }
The find() method returns the value of the first element in the array that satisfies the provided testing function. find()方法返回满足提供的测试功能的数组中第一个元素的值。 Otherwise undefined is returned.
否则返回undefined。
var array1 = [5, 12, 8, 130, 44];
var found = array1.find(function(element) {
return element > 10;
});
console.log(found);
You cannot search
for an element in O(1)
, however you can check if an element exist in a Set
: 您无法在
O(1)
search
元素,但是可以检查Set
是否存在元素:
const set = new Set(array);
if(set.has(3)) console.log("3 is in array");
It is possible, but you must have an JavaScript Object like this: 可能,但是您必须具有这样的JavaScript对象:
var Obj = {
'a':1,
'b':2,
'c':3,
'd':4,
'e':5
};
Without search you can access to your element like this: 无需搜索,您可以像这样访问元素:
console.log(Obj['a']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.