在JavaScript ArrayBuffer对象表示一个固定长度的二进制数据buffer.The byteLength 的属性ArrayBuffer返回一个无符号的32位整数,指定ArrayBuffer的大小/长度。
其语法如下
array.byteLength
请尝试以下示例。
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var arrayBuffer = new ArrayBuffer(8); var result = arrayBuffer.byteLength; document.write("length of the array buffer is: " + result); </script> </body> </html>
输出结果
length of the array buffer is: 8
您还可以通过传递字符串值并获取其长度来创建数组缓冲区对象,如以下示例所示。由于这里我们没有传递任何大小值,它返回0-
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var obj = new ArrayBuffer("Hi welcome to Nhooo"); var byteLength = obj.byteLength; document.write(byteLength); </script> </body> </html>
输出结果
0
创建ArrayBuffer时,不能使用负值,复数,并且大小不能超过2 53,否则此函数会产生错误。
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var obj = new ArrayBuffer(9007199254740995); var byteLength = obj.byteLength; document.write(byteLength); </script> </body> </html>
输出结果
Error: Array buffer allocation failed
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var obj = new ArrayBuffer(2+3i); var byteLength = obj.byteLength; console.log(byteLength); </script> </body> </html>
输出结果
Error: Invalid or unexpected token
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var obj = new ArrayBuffer(-72); var byteLength = obj.byteLength; console.log(byteLength); </script> </body> </html>
输出结果
Error: Invalid array buffer length