JavaScript TypdArray of() 方法从指定数量的参数创建一个新的类型化数组。它返回一个类型化数组实例,其中包含作为参数提供的元素。参数必须与结果类型化数组的元素的类型相同。
如果我们将参数值传递为 'undefined' 或 'empty',它将创建一个元素值为 0 的新类型化数组。
语法
以下是 JavaScript TypedArray of() 方法的语法 -
TypedArray.of(element1, element2, /*..., */ elementN)
参数
此方法接受多个相同类型的参数,即:'element1'、'element2'、....'elementN'。下面描述相同 -
- element1,..., elementN − 用于创建新类型化数组的元素。
返回值
此方法返回新类型化数组的实例。
示例 1
如果传递了一个 empty('') 字符串,它将被转换为数字 0 并添加到类型化数组中。
在下面的程序中,我们使用 JavaScript TypedArray of() 方法创建一个具有指定 empty('') 参数值的新类型化数组。
<html>
<head>
<title>JavaScript TypedArray of() Method</title>
</head>
<body>
<script>
//Unit8Array
let T_array = Uint8Array.of('');
document.write("The new typed array: ", T_array);
document.write("<br>Length of typed array: ", T_array.length);
</script>
</body>
</html>
输出
上面的程序创建了一个新的类型化数组 [0]。
Length of typed array: 1
示例 2
如果我们将多个相同类型的参数传递给此方法,它将使用这些参数值创建一个新的类型化数组。
以下是 JavaScript TypedArray of() 方法的另一个示例。我们使用此方法使用指定的值 '10'、'20'、'30'、'40' 和 '50' 创建一个新的类型化数组。
<html>
<head>
<title>JavaScript TypedArray of() Method</title>
</head>
<body>
<script>
//Unit16Array
let ele1 = '10';
let ele2 = '20';
let ele3 = '30';
let ele4 = '40';
let ele5 = '50';
document.write("Element1 = ", ele1);
document.write("<br>Element2 = ", ele2);
document.write("<br>Element3 = ", ele3);
document.write("<br>Element4 = ", ele4);
document.write("<br>Element5 = ", ele5);
let T_array = Uint16Array.of(ele1, ele2, ele3, ele4, ele5);
document.write("<br>The new typed array: ", T_array);
document.write("<br>Length of typed array: ", T_array.length);
</script>
</body>
</html>
输出
执行上述程序后,它将返回新类型化数组的实例 -
Element2 = 20
Element3 = 30
Element4 = 40
Element5 = 50
The new typed array: 10,20,30,40,50
Length of typed array: 5
示例 3
如果我们将 'undefined' 作为参数传递给 of() 方法,它将创建一个值为 0 的新类型化数组。
在下面的示例中,我们使用类型化数组 of() 方法创建一个具有指定参数值 'undefined' 的新类型化数组。
<html>
<head>
<title>JavaScript TypedArray of() Method</title>
</head>
<body>
<script>
//Unit8Array
let T_array = Uint8Array.of(undefined);
document.write("The new typed array: ", T_array);
document.write("<br>Length of typed array: ", T_array.length);
</script>
</body>
</html>
输出
执行上述程序后,它会创建一个元素值为 0 的新类型化数组。
Length of typed array: 1
示例 4
如果该方法的此值不是有效的类型化数组构造函数,则 of() 方法将引发 'TypeError' 异常。例如,如果您尝试对数字、字符串或对象调用该方法,您将收到 TypeError。
<html>
<head>
<title>JavaScript TypedArray of() Method</title>
</head>
<body>
<script>
try {
let T_array = "Hello".of(1, 2, 3);
document.write("The new typed array: ", T_array);
document.write("<br>Length of typed array: ", T_array.length);
} catch (error) {
document.write(error);
}
</script>
</body>
</html>
输出
上述程序引发 'TypeError' 异常 -

