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
广告

© . All rights reserved.