📜  Underscore.js _.snapshot() 方法

📅  最后修改于: 2022-05-13 01:56:44.313000             🧑  作者: Mango

Underscore.js _.snapshot() 方法

_.snapshot() 方法用于深度快照或克隆给定对象。

句法:

_.snapshot( obj );

参数:此方法需要一个对象来创建一个深度克隆。

返回值:此方法返回一个克隆对象。

注意:这在普通 JavaScript 中不起作用,因为它需要安装 underscore.js contrib 库。

Underscore.js contrib 库可以使用npm install underscore-contrib –save 安装。

示例 1:

Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
var given_Object = { 1:"a", 2:"b" };
var obj = _.snapshot(given_Object);;
  
console.log("Cloned Object: ", obj);


Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
var given_Object = [ 1, 2 ,3 ,4 ];
var obj = _.snapshot(given_Object);;
  
console.log("Cloned Object: ", obj);


Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
var given_Object = "GeeksforGeeks"
var obj = _.snapshot(given_Object);;
  
console.log("Cloned Object: ", obj);


Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
var given_Object = 10000;
var obj = _.snapshot(given_Object);;
  
console.log("Cloned Object: ", obj);


输出:

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

示例 2:此方法也适用于数组。

Javascript

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
var given_Object = [ 1, 2 ,3 ,4 ];
var obj = _.snapshot(given_Object);;
  
console.log("Cloned Object: ", obj);

输出:

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

示例 3:此方法也适用于字符串。

Javascript

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
var given_Object = "GeeksforGeeks"
var obj = _.snapshot(given_Object);;
  
console.log("Cloned Object: ", obj);

输出:

Cloned Object:  GeeksforGeeks

示例 4:

Javascript

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
var given_Object = 10000;
var obj = _.snapshot(given_Object);;
  
console.log("Cloned Object: ", obj);

输出:

Cloned Object:  10000