JavaScript TypedArray indexOf() 方法用于检索找到或定位指定元素的第一个索引。如果指定的元素在类型化数组中重复两次,该方法将优先出现第一次并返回其索引,而不是第二次。
如果我们为此方法指定 fromIndex 参数值,它将开始从指定的 fromIndex 中搜索元素。如果在 fromIndex 和类型化数组的最后一个索引之间找不到该元素,则返回 −1,即使该元素存在于类型化数组中也是如此。
语法
以下是 JavaScript TypedArray indexOf() 方法的语法 -
indexOf(searchElement, fromIndex)
参数
此方法接受两个名为 'searchElement' 和 'fromIndex' 的参数。与下面描述的相同 -
- searchElement - 要搜索的元素。
- fromIndex − 开始搜索的从零开始的索引(位置)。
返回值
此方法返回 searchElement 的第一个索引。
示例 1
如果我们省略 fromIndex 参数并仅将 searchElement 参数传递给此方法,它将在整个类型化数组中搜索此元素,并返回找到 searchElement 的第一个索引。
在下面的程序中,我们使用 JavaScript TypedArray indexOf() 方法来检索此类型化数组 [1, 2, 3, 4, 5, 6, 7, 8] 中指定元素 2 的第一个索引。
<html>
<head>
<title>JavaScript TypedArray indexof() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
document.write("Original TypedArray: ", T_array);
const searchElement = 3;
document.write("<br>searchElement: ", searchElement);
document.write("<br>The element ", searchElement, " is found at position ", T_array.indexOf(searchElement));
</script>
</body>
</html>
输出
上面的程序将第一个索引返回为 '2'。
searchElement: 3
The element 3 is found at position 2
示例 2
如果我们将 searchElement 和 fromIndex 参数都传递给此方法,它将开始在指定的 fromIndex 位置搜索指定的 searchElement。
在这个 JavaScript TypedArray indexOf() 方法的示例中,我们尝试检索指定元素 60 的第一个索引,从此类型化数组中的指定 fromIndex 位置 4 开始搜索:[10, 20, 30, 40, 50, 60, 70, 80, 60]。
<html>
<head>
<title>JavaScript TypedArray indexof() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([10, 20, 30, 40, 50, 60, 70, 80, 60]);
document.write("Original TypedArray: ", T_array);
const searchElement = 60;
const fromIndex = 4;
document.write("<br>searchElement: ", searchElement);
document.write("<br>fromIndex: ", fromIndex);
document.write("<br>The element ", searchElement, " is found at position ", T_array.indexOf(searchElement, fromIndex));
</script>
</body>
</html>
输出
执行上述程序后,它将返回第一个索引为 5。
searchElement: 60
fromIndex: 4
The element 60 is found at position 5
示例 3
如果类型化数组中不存在指定的元素,则 indexOf() 方法返回 -1。
在此示例中,我们对类型化数组使用 indexOf() 方法来检索元素 50 的第一个索引。但是,在 fromIndex 4 和类型化数组 [10, 20, 50, 30, 90, 70] 的最后一个索引之间不存在此元素。
<html>
<head>
<title>JavaScript TypedArray indexof() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([10, 20, 50, 30, 90, 70]);
document.write("Original TypedArray: ", T_array);
const searchElement = 50;
const fromIndex = 4;
document.write("<br>searchElement: ", searchElement);
document.write("<br>fromIndex: ", fromIndex);
document.write("<br>The element ", searchElement, " is found at position ", T_array.indexOf(searchElement, fromIndex));
</script>
</body>
</html>
输出
执行上述程序后,它将返回 -1。
searchElement: 50
fromIndex: 4
The element 50 is found at position -1