定义和用法
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
语法
stringObject.indexOf(searchvalue,fromindex)
参数 | 描述 |
---|---|
searchvalue | 必需。规定需检索的字符串值。 |
fromindex | 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。 |
提示和注释
注释:indexOf() 方法对大小写敏感!
注释:如果要检索的字符串值没有出现,则该方法返回 -1。
语法
arr.includes(searchElement) arr.includes(searchElement, fromIndex)
参数说明
参数 | 描述 |
---|---|
searchElement | 必须。需要查找的元素值。 |
fromIndex | 可选。从该索引处开始查找 searchElement。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜索。默认为 0。 |
技术细节
返回值: | 布尔值。如果找到指定值返回 true,否则返回 false。 |
---|---|
JavaScript 版本: | ECMAScript 6 |
使用includes()方法检查NaN
1 2 3 4 5 |
|
这就是用indexOf()方法开始崩溃的地方
1 2 3 4 5 |
|
判断稀疏数组结果不同
1 2 3 4 5 |
|
让我们看看indexOf()方法将如何处理这个操作
1 2 3 4 5 |
|
includes()方法没有区分-0和+0
1 2 |
|
字符串的indexOf和数组中的indexOf的比较
这两个方法都可以接收两个参数
这两个方法在没有查找的指定的字符都返回-1
字符串中的indexOf中的第二个参数支持负数而数组的indexOf不支持
字符串的indexOf在传入参数不是字符串的情况下默认会转换为字符串而数组的indexOf不会进行数据类的转换
字符串的参数不支持负数
let str = "abcd";
let ary = ["a","b","c","d"];
console.log(str.indexOf("a", -1)); //0
console.log(ary.indexOf("a", -1)); //-1
字符串的参数会自动转换
let str = "1";
let ary = ["1"];
console.log(str.indexOf(1)); //0
console.log(ary.indexOf(1)); //-1
字符串的includes和数组中的includes的比较
这两个方法都可以接收两个参数
这两个方法在没有查找的指定的字符都返回false
字符串中的includes中的第二个参数支持负数而数组的includes不支持
字符串的includes在传入参数不是字符串的情况下默认会转换为字符串而数组的includes不会进行数据类的转换
字符串的参数不支持负数
let str = "abcd";
let ary = ["a","b","c","d"];
console.log(str.includes("a", -1)); //true
console.log(ary.includes("a", -1)); //false
字符串的参数会自动转换
let str = "1";
let ary = ["1"];
console.log(str.includes(1)); //true
console.log(ary.includes(1)); //false