3
I wonder if there is a problem if I add this method to javascript arrays, and if possible how do I do it? It’s something like this?
Array.prototype.search = function () {};
3
I wonder if there is a problem if I add this method to javascript arrays, and if possible how do I do it? It’s something like this?
Array.prototype.search = function () {};
1
There are two methods with functionality that may be the one you are looking for:
the method .find
(ES5) that searches for a condition and returns the first element that meets that condition.
the method .includes
(ES6) that searches for an element and returns true|false
, the style of what was done "before" with .indexOf(el) != -1
.
Having said that, a method with the name search
there is no.
To implement methods in the prototype you can define a function where the this
is the array where you want to use the method. For example for the method .includes
there is a polyfill for old browsers, complex good because the method has a second argument to start the search from a given index.
But that can be implemented in a simplistic way, only to know if a given element is in an array or not, like this:
Array.prototype.search = function(el){
return this.indexOf(el) != -1;
}
var respostaA = [1, 2, 3, 4, 5].search(3);
var respostaB = [1, 2, 3, 4, 5].search(6);
console.log(respostaA); // true
console.log(respostaB); // false
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.
Can you explain what this method should do if the answers don’t match what you’re looking for?
– Sergio
It was just to check whether an array was holding a certain value or not.
– user83428
ok, in this case both methods I have indicated do. The most semantic perhaps is the
.includes
for it simply returnstrue|false
if the array stores this value or not.– Sergio
thanks for the answers, before I had to make a loop for crazy, now facilitated.
– user83428