We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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: The Definitive Guide, Seventh Edition、🔗MDN
The text was updated successfully, but these errors were encountered:
indexOf
includes
arr.indexOf(searchElement[, fromIndex])
arr.includes(searchElement[, fromIndex])
两者语法基本一样,第一个参数表示需要查找的元素值,第二个参数fromIndex为可选参数,表示开始查找的位置,默认为 0,若为负数则表示相对数组末尾的偏移。如果偏移后的索引值仍小于 0,则整个数组都将会被查询。
fromIndex
indexOf()和includes()均可以用于判断数组中是否含有某元素,不过前者返回的是搜索到的第一个元素的索引,后者返回一个布尔值。
indexOf()
includes()
另外容易忽略的一点是,indexOf 使用 strict equality 判断 searchElement与数组中元素的关系,而includes() 使用的是 sameValueZero 算法。
searchElement
说人话就是indexOf()使用===判断,而includes()的判断方式除了会认为NaN与自生相等外,其他逻辑与===一致。具体细则可以参考 Draft ECMA-262
===
NaN
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 中的相等性判断
Sorry, something went wrong.
No branches or pull requests
The text was updated successfully, but these errors were encountered: