Specifikace ES2016 zahrnovaly includes()
metoda pro datovou strukturu pole. includes()
metoda kontroluje, zda pole obsahuje určitý prvek, vrací true
nebo false
podle potřeby.
Ale v ES5 jsme zvyklí provádět operace jako je tato s indexOf()
metoda.
Pomocí includes()
metoda.
const array = [1,2,3,4,5,6];
if(array.includes(4) ){
console.log("true 4 was found in the array")// true 4 was found in the array
}
Proveďme stejnou operaci s indexOf()
metoda.
const array = [1,2,3,4,5,6];
if(array.indexOf(4) > -1 ){
console.log("true 4 was found in the array")// true 4 was found in the array
}
Pomocí includes()
metoda pro kontrolu NaN
 const array = [NaN];
if (array.includes(NaN)){
console.log("true. NAN was found in the array");// true. NAN was found in the array
}
To je místo, kde se věci začínají rozpadat s indexOf()
metoda.
const array = [NaN];
if (array.indexOf(NaN) == -1){
console.log("NaN not found in the array");//NaN not found in the array
}
Kontrola undefined
s includes()
metoda.
const array = [, , , ,];
if(array.includes(undefined)){
console.log("true array elements are undefined");// true array elements are undefined
}
Podívejme se, jak indexOf()
metoda tuto operaci zvládne.
const array = [, , , ,];
if(!array.indexOf(undefined) == -1 ){
console.log("true. array elements are undefined");
}else {
console.log("Sorry can't find undefined");// Sorry can't find undefined
}
includes()
metoda nerozlišuje mezi -0 a +0
const a = [-0].includes(+0);
console.log(a);//true
Typed Arrays bude mít také metodu includes()
let array = Uint8Array.of(2,6,4);
console.log(array.includes(4));//true
Souhrn
- Metoda include najde NaN a nedefinováno zatímco metoda indexOf nikoli.
- Metoda include() nerozlišuje mezi -0 a +0 (Toto není chyba, ale je jasné, jak javascript funguje. Zkontrolujte typ čísla javascriptu)
- Přečtěte si další informace o Array.prototype.includes() od MDN