当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Javascript typedArray.filter()用法及代码示例


typedArray.filter()是javascript中的内置函数,用于生成一个新的typedArray,其元素满足提供的函数所实现的测试。句法:

typedarray.filter(callback)

参数:它采用参数“callback”函数,该函数检查提供的条件满足的typedArray的每个元素。回调函数采用以下指定的三个参数-

  • element:它是元素的值。
  • index:它是元素的索引。
  • array:遍历的是数组。

返回值:它返回带有满足测试条件的元素的新的typedarray。


JavaScript代码显示此函数的工作方式:

<script> 
  
   // Calling isNegative function to check 
   // elements of the typedArray 
   function isNegative(element, index, array) 
   { 
    return element < 0; 
   } 
  
   // Created some typedArrays. 
   const A = new Int8Array([ -10, 20, -30, 40, -50 ]); 
   const B = new Int8Array([ 10, 20, -30, 40, -50 ]); 
   const C = new Int8Array([ -10, 20, -30, 40, 50 ]); 
   const D = new Int8Array([ -10, 20, 30, 40, -50 ]); 
  
   // Calling filter() function to check condition 
   // provided by its parameter 
   const a = A.filter(isNegative); 
   const b = B.filter(isNegative); 
   const c = C.filter(isNegative); 
   const d = D.filter(isNegative); 
  
   // Printing the filtered typedArray 
   document.write(a +"<br>"); 
   document.write(b +"<br>"); 
   document.write(c +"<br>"); 
   document.write(d); 
     
</script>

输出:

-10,-30,-50
-30,-50
-10,-30
-10,-50



注:本文由纯净天空筛选整理自ShivamKD大神的英文原创作品 JavaScript | typedArray.filter() with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。