JavaScript - TypedArray some() 方法



JavaScript TypedArray 的some() 方法用於檢查 TypedArray 中是否至少有一個元素透過提供的函式實現的測試。如果至少有一個元素透過測試,則該方法返回布林值'true',否則返回'false'。需要注意的是,此方法不會修改原始 TypedArray,而是返回一個新的 TypedArray。

以下是一些關於 'some()' 方法的補充說明:

  • some() 方法作用於 TypedArray(例如 Uint8Array、Int16Array 等)。

  • 它接受一個測試函式作為引數。

  • 測試函式針對 TypedArray 中的每個元素執行。

  • 如果某個元素滿足測試函式指定的條件(返回 true 值)。

語法

以下是 JavaScript TypedArray some() 方法的語法:

some(callbackFn, thisArg)

引數

此方法接受兩個名為 'callbackFn' 和 'thisArg' 的引數,如下所述:

callbackFn - 此引數是一個測試函式,將針對 TypedArray 中的每個元素執行。

此函式接受三個名為 'element'、'index' 和 'array' 的引數。以下是每個引數的描述:

  • element - 表示 TypedArray 中當前正在處理的元素。

  • index - 指示 TypedArray 中當前元素的索引(位置)。

  • array - 指的是整個 TypedArray。

thisArg (可選) - 此引數是可選的,允許您指定 this 在 callbackFn 中的值。

返回值

如果 TypedArray 中至少有一個元素透過提供的函式實現的測試,則此方法返回 true;否則返回 false。

示例

示例 1

如果 TypedArray 中至少有一個元素透過 callbackFn 函式測試,則此方法將返回 true

在以下示例中,我們使用 JavaScript TypedArray 的 some() 方法來確定 TypedArray [1, 2, 3, 4, 5, 6, 7] 中是否至少有一個元素透過 isEven() 函式實現的測試。此函式檢查 TypedArray 中的偶數,我們將此函式作為引數傳遞給 some() 方法。

<html>
<head>
   <title>JavaScript TypedArray some() Method</title>
</head>
<body>
   <script>
      function isEven(element, index, array){
         return element % 2 == 0;
      }
      const T_array = new Int8Array([1, 2, 3, 4, 5, 6, 7]);
      document.write("The typed array elements are: ", T_array);
      
      //using some() method
      document.write("<br>Is this typed array ", T_array, " contain at least one even number? ", T_array.some(isEven));
   </script>    
</body>
</html>

輸出

以上程式返回 'true'。

The typed array elements are: 1,2,3,4,5,6,7
Is this typed array 1,2,3,4,5,6,7 contain at least one even number? true

示例 2

如果 TypedArray 中沒有一個元素透過 callbackFn 函式測試,則 some() 方法將返回 false

以下是 JavaScript TypedArray some() 函式的另一個示例。我們使用此方法來檢查是否至少有一個元素透過 isNegative() 函式提供的測試。我們將此函式作為引數傳遞給此方法,它檢查 TypedArray 中的負數。

<html>
<head>
   <title>JavaScript TypedArray some() Method</title>
</head>
<body>
   <script>
      function isNegative(element, index, array){
         return element < 0;
      }
      const T_array = new Int8Array([10, 20, 30, 40, 50, 60, 70, 80]);
      document.write("The typed array elements are: ", T_array);
      
      //using some() method
      document.write("<br>Is this typed array ", T_array, " contain at least one negative number? ", T_array.some(isNegative));
   </script>    
</body>
</html>

輸出

執行以上程式後,它將返回 'false'。

The typed array elements are: 10,20,30,40,50,60,70,80
Is this typed array 10,20,30,40,50,60,70,80 contain at least one negative number? false
廣告