JavaScript - TypedArray indexof() 方法
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() 方法检索此类型数组中指定元素 2 的第一个索引[1, 2, 3, 4, 5, 6, 7, 8].
<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"。
Original TypedArray: 1,2,3,4,5,6,7,8 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。
Original TypedArray: 10,20,30,40,50,60,70,80,60 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。
Original TypedArray: 10,20,50,30,90,70 searchElement: 50 fromIndex: 4 The element 50 is found at position -1

