JavaScript - TypedArray of() 方法
JavaScript TypdArray 的 of() 方法根据指定的可变数量参数创建一个新的类型化数组。它返回一个包含作为参数提供的元素的类型化数组实例。参数必须与结果类型化数组的元素类型相同。
如果我们将参数值传递为 'undefined' 或 'empty',它将创建一个元素值为 0 的新类型化数组。
这是一个 静态 方法,这意味着它可以在不创建 TypedArray 对象实例的情况下调用(就像 TypedArray.of() 一样)。 TypedArray 对象可以是 TypedArray 的任何子类,例如 Uint8Array、Int16Array 等。
语法
以下是 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]。
The new typed array: 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>
输出
上述程序执行后,将返回新类型数组的实例,如下所示:
Element1 = 10 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。
The new typed array: 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"异常 -
TypeError: "Hello".of is not a function

