js indexof
时间: 2024-10-20 08:49:14
(部分内容来自网络,其真实性存疑,为了避免对您造成误导,请谨慎甄别。)
indexOf()
是 JavaScript 中的一个数组和字符串的方法,用于查找指定元素或子字符串在数组或字符串中的第一次出现的位置。如果未找到该元素或子字符串,indexOf()
将返回 -1
。
1. Array.prototype.indexOf()
语法
javascriptarray.indexOf(searchElement, fromIndex)
- searchElement
:要查找的元素。
- fromIndex
(可选):开始查找的位置,默认为 0
。可以是负数,表示从数组末尾开始计算。
示例
javascriptconst array = [2, 5, 9, 2, 5];
// 查找元素 5 的索引
const index1 = array.indexOf(5);
console.log(index1); // Output: 1
// 查找元素 2 的第一次出现索引
const index2 = array.indexOf(2);
console.log(index2); // Output: 0
// 从索引 1 开始查找元素 2(只查找后面的部分)
const index3 = array.indexOf(2, 1);
console.log(index3); // Output: 3
// 查找不存在的元素,返回 -1
const index4 = array.indexOf(10);
console.log(index4); // Output: -1
2. String.prototype.indexOf()
语法
javascriptstring.indexOf(searchValue, fromIndex)
- searchValue
:要查找的子字符串。
- fromIndex
(可选):开始查找的位置,默认为 0
。可以是负数,表示从字符串末尾开始计算。
示例
javascriptconst str = "Hello, world! Hello, JavaScript!";
// 查找子字符串 "Hello"
const index1 = str.indexOf("Hello");
console.log(index1); // Output: 0
// 查找子字符串 "world"
const index2 = str.indexOf("world");
console.log(index2); // Output: 7
// 从索引 8 开始查找 "Hello"
const index3 = str.indexOf("Hello", 8);
console.log(index3); // Output: 13
// 查找不存在的子字符串
const index4 = str.indexOf("Python");
console.log(index4); // Output: -1
注意事项
- indexOf()
方法是区分大小写的。
- 如果 searchElement
或 searchValue
是 undefined
、null
或 NaN
,它们会被视为有效的查找值。
- fromIndex
参数可以是负数,例如 -1
表示从字符串或数组的最后一个元素开始查找。
总结
indexOf()
是一个非常实用的方法,可用于查找数组或字符串中的元素位置。当需要知道一个元素或子字符串的位置时,它提供了一种简单而有效的方式。对于数组和字符串的查找,使用 indexOf()
是常见的做法,尤其是在进行条件判断时。