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


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


Lodash是一個JavaScript庫,可在underscore.js之上運行。 Lodash幫助處理數組,字符串,對象,數字等。

_.snapshot()方法用於深度快照或克隆給定對象。

用法:

_.snapshot( obj )

參數:此方法采用一個對象來創建深層克隆。

返回值:此方法返回克隆的對象。



注意:由於它需要安裝lodash contrib庫,因此在正常的JavaScript中將無法使用。可以使用npm install lodash-contrib -save安裝Lodash contrib庫。

範例1:

Javascript

// Defining the lodash-contrib variable  
var _ = require('lodash-contrib'); 
  
// The given object 
var given_object = 
  { "a":100, "b":200, "c":300 };  
  
// Using the _.snapshot() method 
// to create the deep clone 
var cloned_obj = _.snapshot(given_object); 
    
console.log("Cloned Object:", cloned_obj);

輸出:

Cloned Object:Object {1:"a", 2:"b"}

範例2:

Javascript

// Defining the lodash-contrib variable  
var _ = require('lodash-contrib'); 
  
// The given array 
var given_array = [5, 10, 15, 20, 25];  
  
// Using the _.snapshot() method 
// to create the deep clone 
var cloned_arr = _.snapshot(given_array); 
    
console.log("Cloned Array:", cloned_arr);

輸出:

Cloned Object:[1, 2, 3, 4]

範例3:

Javascript

// Defining the lodash-contrib variable  
var _ = require('lodash-contrib'); 
  
// The given string 
var given_string = "GeeksforGeeks"
  
// Using the _.snapshot() method 
// to create the deep clone 
var cloned_string = _.snapshot(given_string); 
    
console.log("Cloned String:", cloned_string);

輸出:

Cloned Object:GeeksforGeeks

範例4:

Javascript

// Defining the lodash-contrib variable  
var _ = require('lodash-contrib'); 
  
// The given number 
var given_number = 789434; 
  
// Using the _.snapshot() method 
// to create the deep clone 
var cloned_num = _.snapshot(given_number); 
    
console.log("Cloned Number:", cloned_num);

輸出:

Cloned Object:10000

相關用法


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