And includes the difference indexOf

Since ES6 deployment includes methods like indexOf loses its arena, and in the end what indexOf inadequate, this article will introduce the differences between the two methods.

 

Look a function, they look at the return value is a return value type, a boolean is returned, it includes much simpler if the conditions at the time of judgment, and indexOf need to write a condition to judge.

 

var = [1];

if (ary.indexOf(1) !== -1) {

    the console.log ( "Array present 1")

}

if (ary.includes(1)) {

    the console.log ( "Array present 1")

}

 

If there is NaN array, and you just need to determine whether there exists an array of NaN, then you can not be judged using indexOf, you must use includes this method.

 

ary1 var = [at];

console.log(ary1.indexOf(NaN))//-1

console.log(ary1.includes(NaN))//true

 

When the value of the empty array, includes think-empty value is undefined, and indexOf not.

 

var ary1 = new Array(3);

console.log(ary1.indexOf(undefined));//-1

console.log(ary1.includes(undefined))//true

 

Summary, in the end when to use and when to use indexOf includes still depends on the circumstances to decide if you want to find the location of an element in the array, you can use indexOf, if you just want to know whether there is an element in the array, the method you use includes more appropriate.

Guess you like

Origin www.cnblogs.com/ygunoil/p/12339873.html
Recommended