简体   繁体   中英

TypeError: Cannot convert undefined or null to object, using array.includes

I don't understand why the following code throws a "TypeError: Cannot convert undefined or null to object"

const array = [1, 2];

[3, 4].every(array.includes);

You didn't bind it

const array = [1, 2];

const r1 = [1, 2].every(array.includes.bind(array));
const r2 = [3, 4].every(array.includes.bind(array));

--- edit

The above is incorrect, because the every callback takes the index of the current item as the second parameter, but array.includes takes the fromIndex as the second parameter. Thanks to Nina Scholz in the comments.

What you want is

[1,2].every(n => arr.includes(n));

You need to pass a function to .every() which takes the current element as parameter:

[3, 4].every(element => array.includes(element));

 const array = [1, 2]; console.log( [3, 4].every(element => array.includes(element)) ); console.log( [1, 2].every(element => array.includes(element)) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM