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


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

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

lodash中Object的_.extendWith()方法與_.assignIn()方法相似,唯一的區別是它接受為生成分配值而調用的定製程序。此外,如果此處使用的定製程序返回未定義,則分配由方法處理。

注意:

  • 可以使用五個自變量調用此處使用的定製器,即objValue,srcValue,鍵,對象和源。
  • 通過此方法可以更改此處使用的對象。

用法:

_.extendWith(object, sources, [customizer])

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



  • object:它是目標對象。
  • sources:它是源對象。
  • customizer:它是自定義分配值的函數。

返回值:此方法返回一個對象。

範例1:

// Requiring lodash library 
const _ = require('lodash'); 
  
// Defining a function customizer 
function customizer(objectVal, sourceVal) { 
  return _.isUndefined(objectVal) ?  
        sourceVal:objectVal; 
} 
  
// Calling extendWith method with its parameter 
let obj = _.extendWith({ 'gfg':1 },  
        { 'geek':3 }, customizer); 
  
// Displays output 
console.log(obj);

輸出:

{ gfg:1, geek:3 }

範例2:

// Requiring lodash library 
const _ = require('lodash'); 
  
// Defining a function customizer 
function customizer(objectVal, sourceVal) { 
  return _.isUndefined(objectVal) ?  
        sourceVal:objectVal; 
} 
  
// Defining a function GfG 
function GfG() { 
  this.p = 7; 
} 
  
// Defining a function Portal 
function Portal() { 
  this.r = 9; 
} 
  
// Defining prototype of above functions 
GfG.prototype.q = 8; 
Portal.prototype.s = 10; 
  
// Calling extendWith method 
// with its parameter 
let obj = _.extendWith({ 'p':6 },  
    new GfG, new Portal, customizer); 
  
// Displays output 
console.log(obj);

輸出:

{ p:6, q:8, r:9, s:10 }

參考: https://lodash.com/docs/4.17.15#assignInWith




相關用法


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