當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Lodash _.flatMapDepth()用法及代碼示例

Lodash是一個JavaScript庫,可在underscore.js頂部使用。 Lodash幫助處理數組,集合,字符串,對象,數字等。

_.flatMapDepth()方法通過iteratee函數運行給定集合中的每個元素,從而創建一個扁平化的值數組。它遞歸地將映射結果展平到給定的深度值。它類似於_.flatMap()方法。

用法:

_.flatMapDepth( collection, iteratee, depth )

參數:此方法接受上述和以下所述的三個參數:

  • collection:它是要迭代的集合。
  • iteratee:每次迭代調用的函數。
  • depth:該數字指定最大遞歸深度。它是一個可選參數。預設值為1。

返回值:此方法返回新的展平的數組。



範例1:

// Requiring the lodash library  
const _ = require("lodash");  
      
// Original array  
var users = ([3, 4]); 
  
// Using the _.flatMapDepth() method 
let flat_map = _.flatMapDepth(users, duplicate, 2 ) 
function duplicate(n) { 
  return [[[n, n]]]; 
} 
  
// Printing the output  
console.log(flat_map);

輸出:

[ [ 3, 3 ], [ 4, 4 ] ]

範例2:

// Requiring the lodash library  
const _ = require("lodash");  
      
// Original array  
var users = (['q', 'r', 't', 'u']); 
  
// Using the _.flatMapDepth() method 
let flat_map = _.flatMapDepth(users, duplicate, 2 ) 
function duplicate(n) { 
  return [[[n, n]]]; 
} 
  
// Printing the output  
console.log(flat_map);

輸出:

[ [ 'q', 'q' ], [ 'r', 'r' ], [ 't', 't' ], ['u', 'u' ] ]

相關用法


注:本文由純淨天空篩選整理自shivanisinghss2110大神的英文原創作品 Lodash _.flatMapDepth() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。