如何将一张地图复制到另一张地图?

发布于 2024-12-17 15:25:55 字数 399 浏览 3 评论 0 原文

如何在 JavaScript 中克隆/复制 Map

我知道如何克隆数组,但如何克隆/复制 Map

var myArray = new Array(1, 2, 3);
var copy    = myArray.slice();
// now I can change myArray[0] = 5; & it wont affect copy array

// Can I just do the same for map?
var myMap = new ?? // in javascript is it called a map?
var myMap = {"1": 1, "2", 2};
var copy  = myMap.slice(); 

How do I clone/copy a Map in JavaScript?

I know how to clone an array, but how do I clone/copy a Map?

var myArray = new Array(1, 2, 3);
var copy    = myArray.slice();
// now I can change myArray[0] = 5; & it wont affect copy array

// Can I just do the same for map?
var myMap = new ?? // in javascript is it called a map?
var myMap = {"1": 1, "2", 2};
var copy  = myMap.slice(); 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

明媚殇 2024-12-24 15:25:55

随着 JavaScript 中地图的引入,考虑到构造函数接受可迭代,这非常简单:

var newMap = new Map(existingMap)

此处的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

With the introduction of Maps in JavaScript it's quite simple considering the constructor accepts an iterable:

var newMap = new Map(existingMap)

Documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

愁杀 2024-12-24 15:25:55

一种简单的方法(进行浅复制)是将源映射的每个属性复制到目标映射:

var newMap = {};
for (var i in myMap)
   newMap[i] = myMap[i];

注意:newMap[i] 很可能是对与 myMap[i] 相同的对象的引用

A simple way (to do a shallow copy) is to copy each property of the source map to the target map:

var newMap = {};
for (var i in myMap)
   newMap[i] = myMap[i];

NOTE: newMap[i] could very well be a reference to the same object as myMap[i]

﹏半生如梦愿梦如真 2024-12-24 15:25:55

如果您需要制作 Map 的深层副本,可以使用以下命令:

new Map(JSON.parse(JSON.stringify(Array.from(source))));

其中 source 是原始 Map 对象。

请注意,这可能并不适合 Map 值不可序列化的所有用例,有关更多详细信息,请参阅:https://stackoverflow.com /a/122704/10583071

If you need to make a deep copy of a Map you can use the following:

new Map(JSON.parse(JSON.stringify(Array.from(source))));

Where source is the original Map object.

Note this may not be suitable for all use cases where the Map values are not serializable, for more details see: https://stackoverflow.com/a/122704/10583071

何以畏孤独 2024-12-24 15:25:55

非常简单,只需使用 Object.assign()

let map = {'a': 1, 'b': 2}
let copy = Object.assign({}, map);

// Or

const copy = Object.assign({}, {'a': 1, 'b': 2});

Very simple to just use Object.assign()

let map = {'a': 1, 'b': 2}
let copy = Object.assign({}, map);

// Or

const copy = Object.assign({}, {'a': 1, 'b': 2});
你又不是我 2024-12-24 15:25:55

JQuery 有一个方法来扩展一个对象(合并两个对象),但是这个方法也可以用于通过提供一个空对象来克隆一个对象。

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

更多信息可以在jQuery 文档中找到。

JQuery has a method to extend an object (merging two objects), but this method can also be used to clone an object by providing an empty object.

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

More information can be found in the jQuery documentation.

懒的傷心 2024-12-24 15:25:55

没有内置任何内容。

要么使用经过良好测试的递归属性复制器,要么如果性能不是问题,则序列化为 JSON 并再次解析为新对象。

There is nothing built in.

Either use a well tested recursive property copier or if performance isn't an issue, serialise to JSON and parse again to a new object.

你怎么敢 2024-12-24 15:25:55

没有内置(编辑:DEEP)克隆/复制。您可以编写自己的方法来浅复制或深复制:

function shallowCopy(obj) {
    var result = {};
    for (var i in obj) {
        result[i] = obj[i];
    }
    return result;
}

function deepCopy(obj) {
    var result = {};
    for (var i in obj) {
        // recursion here, though you'll need some non-trivial logic
        // to avoid getting into an endless loop.
    }
    return result;
}

[编辑]浅复制是内置的,使用Object.assign

let result = Object.assign({}, obj);

全部Javascript 中的对象是动态的,并且可以分配新的属性。您所指的“地图”实际上只是一个空对象。数组也是一个对象,具有slice等方法和length等属性。

There is no built-in (edit: DEEP) clone/copy. You can write your own method to either shallow or deep copy:

function shallowCopy(obj) {
    var result = {};
    for (var i in obj) {
        result[i] = obj[i];
    }
    return result;
}

function deepCopy(obj) {
    var result = {};
    for (var i in obj) {
        // recursion here, though you'll need some non-trivial logic
        // to avoid getting into an endless loop.
    }
    return result;
}

[EDIT] Shallow copy is built-in, using Object.assign:

let result = Object.assign({}, obj);

All objects in Javascript are dynamic, and can be assigned new properties. A "map" as you refer to it is actually just an empty object. An Array is also an object, with methods such as slice and properties like length.

忘东忘西忘不掉你 2024-12-24 15:25:55

我注意到 Map 应该需要特殊处理,因此根据该线程中的所有建议,代码将是:

function deepClone( obj ) {
    if( !obj || true == obj ) //this also handles boolean as true and false
        return obj;
    var objType = typeof( obj );
    if( "number" == objType || "string" == objType ) // add your immutables here
        return obj;
    var result = Array.isArray( obj ) ? [] : !obj.constructor ? {} : new obj.constructor();
    if( obj instanceof Map )
        for( var key of obj.keys() )
            result.set( key, deepClone( obj.get( key ) ) );
    for( var key in obj )
        if( obj.hasOwnProperty( key ) )
            result[key] = deepClone( obj[ key ] );
    return result;
}

I noticed that Map should require special treatment, thus with all suggestions in this thread, code will be:

function deepClone( obj ) {
    if( !obj || true == obj ) //this also handles boolean as true and false
        return obj;
    var objType = typeof( obj );
    if( "number" == objType || "string" == objType ) // add your immutables here
        return obj;
    var result = Array.isArray( obj ) ? [] : !obj.constructor ? {} : new obj.constructor();
    if( obj instanceof Map )
        for( var key of obj.keys() )
            result.set( key, deepClone( obj.get( key ) ) );
    for( var key in obj )
        if( obj.hasOwnProperty( key ) )
            result[key] = deepClone( obj[ key ] );
    return result;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文