How to realize JavaScript (without using any libraries) function inArray, call examples of which are given below?
inArray(15, [1, 10, 145, 8]) === false;
[23, 674, 4, 12].inArray(4) === true;
Thank you very much!
How to realize JavaScript (without using any libraries) function inArray, call examples of which are given below?
inArray(15, [1, 10, 145, 8]) === false;
[23, 674, 4, 12].inArray(4) === true;
Thank you very much!
 
    
    You're looking for indexOf
[23, 674, 4, 12].indexOf(4) >= 0 // evaluates to true
 
    
    You can attach functions to the prototype of Array. That this may cause problems has been thoroughly discussed elsewhere.
function inArray(needle, haystack) {
  return haystack.indexOf(needle) >= 0;
}
Array.prototype.inArray = function(needle) {
  return inArray(needle, this);
}
console.log(inArray(15, [1, 10, 145, 8])); // false
console.log([23, 674, 4, 12].inArray(4));  // true 
    
     
    
    You can use indexOf with ES6 :
var inArray = (num, arr) => (arr.indexOf(num) === -1) ? false : true;
var myArray = [1 ,123, 45];
console.log(inArray(15, myArray)); // false
console.log(inArray(123, myArray));// true
