How to copy/clone a hash/object in JQuery?

前端 未结 6 2151
既然无缘
既然无缘 2021-02-05 00:52

I have a simple object (or hash) in Javascript:

var settings = {
  link: \'http://example.com\',
  photo: \'http://photos.com/me.jpg\'
};

I nee

6条回答
  •  离开以前
    2021-02-05 01:36

    Yes, extend an empty object with the original one; that way, everything will simply be copied:

    var clone = $.extend({}, settings);
    

    Extending some filled object with another, e.g.:

    $.extend({a:1}, {b:2})
    

    will return:

    {a:1, b:2}
    

    With the same logic:

    $.extend({}, {foo:'bar', test:123})
    

    will return:

    {foo:'bar', test:123}
    

    i.e. effectively a clone.

提交回复
热议问题