0

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!

2

4 Answers 4

0

You're looking for indexOf

[23, 674, 4, 12].indexOf(4) >= 0 // evaluates to true
Sign up to request clarification or add additional context in comments.

Comments

0
    function inArray(val, arr){
        return arr.indexOf(val) > -1;
    }

Comments

0

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

Comments

0

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

3 Comments

Yes but arrow functions are not :)
Neiter are they required to use indexOf

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.