Please support this book: buy it (PDF, EPUB, MOBI) or donate
3. Array.prototype.includes
This chapter describes the ECMAScript 2016 feature “Array.prototype.includes
” by Domenic Denicola and Rick Waldron.
3.1 Overview
> ['a', 'b', 'c'].includes('a')
- true
- > ['a', 'b', 'c'].includes('d')
- false
3.2 The Array method includes
The Array method includes
has the following signature:
Array
.
prototype
.
includes
(
value
:
any
)
:
boolean
It returns true
if value
is an element of its receiver (this
) and false
, otherwise:
> ['a', 'b', 'c'].includes('a')
- true
- > ['a', 'b', 'c'].includes('d')
- false
includes
is similar to indexOf
– the following two expressions are mostly equivalent:
arr
.
includes
(
x
)
arr
.
indexOf
(
x
)
>=
0
The main difference is that includes()
finds NaN
, whereas indexOf()
doesn’t:
> [NaN].includes(NaN)
- true
- > [NaN].indexOf(NaN)
- -1
includes
does not distinguish between +0
and -0
(which is how almost all of JavaScript works):
> [-0].includes(+0)
- true
Typed Arrays will also have a method includes()
:
let
tarr
=
Uint8Array
.
of
(
12
,
5
,
3
);
console
.
log
(
tarr
.
includes
(
5
));
// true
3.3 Frequently asked questions
- Why is the method called
includes
and notcontains
?The latter was the initial choice, but that broke code on the web (MooTools adds this method toArray.prototype
). - Why is the method called
includes
and nothas
?has
is used for keys (Map.prototype.has
),includes
is used for elements (String.prototype.includes
). The elements of a Set can be viewed as being both keys and values, which is why there is aSet.prototype.has
(and noincludes
). - The ES6 method
String.prototype.includes
works with strings, not characters. Isn’t that inconsistent w.r.t.Array.prototype.includes
?If Arrayincludes
worked exactly like stringincludes
, it would accept arrays, not single elements. But the twoincludes
follow the example ofindexOf
; characters are seen as a special case and strings with arbitrary lengths as the general case.
3.4 Further reading
Array.prototype.includes
(Domenic Denicola, Rick Waldron)
当前内容版权归 exploringjs.com 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 exploringjs.com .