ArrayBuffer.byteLength 屬性(JavaScript)


JavaScript 中的 ArrayBuffer 物件表示一個固定長度的二進位制資料緩衝區。ArrayBufferbyteLength 屬性返回一個無符號 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 Tutorialspoint");
      var byteLength = obj.byteLength;
      document.write(byteLength);
   </script>
</body>
</html>

輸出

0

錯誤

在建立 ArrayBuffer 的同時,你不能使用負值或複數,且大小不能大於 253,否則此函式將產生一個錯誤。

大小大於 253

<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

更新於: 25-Jun-2020

538 次瀏覽

開啟你的 事業

完成該課程以獲得認證

開始
廣告
© . All rights reserved.