Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript/Array #19

Open
canvascat opened this issue Jun 7, 2021 · 1 comment
Open

JavaScript/Array #19

canvascat opened this issue Jun 7, 2021 · 1 comment

Comments

@canvascat
Copy link
Owner

数组知识查漏补缺,主要来源:📖 JavaScript: The Definitive Guide, Seventh Edition、🔗MDN

@canvascat
Copy link
Owner Author

canvascat commented Jun 7, 2021

indexOf & includes

  • arr.indexOf(searchElement[, fromIndex])
  • arr.includes(searchElement[, fromIndex])

两者语法基本一样,第一个参数表示需要查找的元素值,第二个参数fromIndex为可选参数,表示开始查找的位置,默认为 0,若为负数则表示相对数组末尾的偏移。如果偏移后的索引值仍小于 0,则整个数组都将会被查询。

indexOf()includes()均可以用于判断数组中是否含有某元素,不过前者返回的是搜索到的第一个元素的索引,后者返回一个布尔值。

另外容易忽略的一点是,indexOf 使用 strict equality 判断 searchElement与数组中元素的关系,而includes() 使用的是 sameValueZero 算法。

说人话就是indexOf()使用===判断,而includes()的判断方式除了会认为NaN与自生相等外,其他逻辑与===一致。具体细则可以参考 Draft ECMA-262

const a = [1, true, 3, NaN];
a.includes(true); // => true
a.includes(2); // => false
a.includes(NaN); // => true
a.indexOf(NaN); // => -1; indexOf can't find NaN

扩展阅读:JavaScript 中的相等性判断

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant