JavaScript TypedArray with() 方法用于更改给定索引的值。它返回一个新的类型化数组,其中 index 处的元素替换为指定值。
如果索引参数值小于或大于类型化数组长度,则此方法会引发 'RangeError' 异常。
语法
以下是 JavaScript TypedArray with() 方法的语法 -
arrayInstance.with(index, value)
参数
- index − 值将替换或更改的从零开始的索引。
- value − 要在指定索引处插入或分配的值。
返回值
此方法返回一个新的类型化数组,其中指定索引处的元素替换为 value。
示例 1
将第一个元素 (index = 0) 的值替换为指定的值。
在下面的示例中,我们使用 JavaScript TypedArray with() 方法将指定索引 0 处的这个类型化数组 [10, 20, 30, 40, 50] 元素更改(或替换)为值 10。
<html>
<head>
<title>JavaScript TypedArray with() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([10, 20, 30, 40, 50]);
document.write("Typed array: ", T_array);
const index = 0;
const value = 0;
document.write("<br>Index: ", index);
document.write("<br>Value: ", value);
var new_arr = ([]);
//using with() method
new_arr = T_array.with(index, value);
document.write("<br>New typed array after replacing value at specified index: ", new_arr);
</script>
</body>
</html>
输出
一旦执行了上面的程序,它将在替换 [0, 20, 30, 40, 50] 后返回一个新的类型化数组。
Typed array: 10,20,30,40,50
Index: 0
Value: 0
New typed array after replacing value at specified index: 0,20,30,40,50
Index: 0
Value: 0
New typed array after replacing value at specified index: 0,20,30,40,50
示例 2
以下是 JavaScript TypedArray with() 方法的另一个示例。我们使用此方法将指定索引 3 处的这个类型化数组 [1, 2, 3, 4, 5, 6, 7] 的值更改(或替换)为给定值 10。
<html>
<head>
<title>JavaScript TypedArray with() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2, 3, 4, 5, 6, 7] );
document.write("Typed array: ", T_array);
const index = 3;
const value = 10;
document.write("<br>Index: ", index);
document.write("<br>Value: ", value);
var new_arr = ([]);
//using with() method
new_arr = T_array.with(index, value);
document.write("<br>New typed array after replacing value at specified index: ", new_arr);
</script>
</body>
</html>
输出
上面的程序返回一个新的类型化数组 [1,2,3,10,5,6,7]。
Typed array: 1,2,3,4,5,6,7
Index: 3
Value: 10
New typed array after replacing value at specified index: 1,2,3,10,5,6,7
Index: 3
Value: 10
New typed array after replacing value at specified index: 1,2,3,10,5,6,7
示例 3
如果 index 参数值大于类型化数组长度,它将引发 'RangeError' 异常。
<html>
<head>
<title>JavaScript TypedArray with() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([10, 20, 30, 40, 50, 60, 70, 80]);
document.write("Typed array: ", T_array);
const index = 10;
const value = 1;
document.write("<br>Index: ", index);
document.write("<br>Value: ", value);
document.write("<br>Typed array length: ", T_array.length);
const new_arr = ([]);
try {
new_arr = T_array.with(index, value);
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
执行上述程序后,将抛出 RangeError 异常。
Typed array: 10,20,30,40,50,60,70,80
Index: 10
Value: 1
Typed array length: 8
RangeError: Invalid typed array index
Index: 10
Value: 1
Typed array length: 8
RangeError: Invalid typed array index