Nodejs:如何克隆对象 [英] Nodejs: how to clone an object

查看:203
本文介绍了Nodejs:如何克隆对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我克隆一个数组,我使用 cloneArr = arr.slice()

If I clone an array, I use cloneArr = arr.slice()

我想知道如何在nodejs中克隆一个对象。

I want to know how to clone an object in nodejs.

推荐答案

对于没有必要挤压每一滴性能的实用程序和类,我经常作弊并只使用JSON来执行深层复制:

For utilities and classes where there is no need to squeeze every drop of performance, I often cheat and just use JSON to perform a deep copy:

function clone(a) {
   return JSON.parse(JSON.stringify(a));
}

这不是唯一的答案或最优雅的答案;所有其他答案都应该考虑到生产瓶颈。但是,这是一个快速而肮脏的解决方案,非常有效,并且在我克隆一个简单的属性哈希的大多数情况下非常有用。

This isn't the only answer or the most elegant answer; all of the other answers should be considered for production bottlenecks. However, this is a quick and dirty solution, quite effective, and useful in most situations where I would clone a simple hash of properties.

这篇关于Nodejs:如何克隆对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆