JavaScript - TypedArray with() 方法
JavaScript TypedArray with() 方法用于更改给定索引的值。返回一个新的类型化数组,其索引处的元素将被替换为指定值。
如果索引参数值小于或大于类型化数组的长度,则此方法抛出 'RangeError' 异常。
语法
以下是 JavaScript TypedArray with() 方法的语法 -
arrayInstance.with(index, value)
参数
index - 将从零开始的索引,值将被替换或更改。
value - 要在指定索引处插入或赋值的值。
返回值
此方法返回一个新的类型化数组,其中指定索引处的元素被替换为值。
示例
示例 1
将第一个元素(索引 = 0)的值替换为指定的值。
在下面的示例中,我们使用 JavaScript TypedArray 的 with() 方法将类型化数组 [10, 20, 30, 40, 50] 中指定索引 0 处的元素更改(或替换)为值 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 = ([]);
//使用 with() 方法
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
示例 2
以下是 JavaScript TypedArray with() 方法的另一个示例。我们使用此方法将类型数组 [1, 2, 3, 4, 5, 6, 7] 中指定索引 3 处的值更改(或替换)为给定值 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 = ([]);
//使用 with() 方法
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
示例 3
如果索引参数值大于类型数组的长度,则会抛出"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

