簡體   English   中英

在javascript中將值從一個字典復制到另一個字典

[英]to copy the values from one dictionary to other dictionary in javascript

以下代碼段無法將內容從一個字典復制到另一個字典。 它拋出一個顯示“copy.Add不是函數”的類型錯誤。 有人可以建議將鍵值對從一個字典復制到另一個字典的方法。

dict = {"Name":"xyz", "3": "39"};
var copy={};
console.log(dict);
for(var key in dict)
{
   copy.Add(key, dict[key]);
}
console.log(copy);

你不需要在copy -variable`上調用add 您可以直接使用索引器,如下所示:

dict = {"Name":"xyz", "3": "39"};
var copy = {};
console.log(dict);
for(var key in dict)
{
    copy[key] = dict[key];
}
console.log(copy);

在Javascript中,使用Object.assign(copy, dict)將內容復制到另一個已存在的字典中(即“就地”副本):

dict = {"Name":"xyz", "3": "39"};
var copy={};
console.log(dict, copy);
Object.assign(copy, dict);
console.log(dict, copy);

在較新的JavaScript版本中,您還可以使用...運算符將dict克隆到新的dict中(此方法創建一個新實例):

var copy = {...dict};

額外:您還可以使用此語法組合(合並)兩個詞典。 就地:

Object.assign(copy, dict1, dict2);

或者通過創建一個新實例:

var copy = {...dict1, ...dict2};

您的代碼不是C#代碼,正確的方法是,

Dictionary<string, string> dictionary1 =  new Dictionary<string, string>();
Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
dictionary1.Add("Name", "xyz");
dictionary1.Add("3", "39");
foreach(KeyValuePair<string,string> val in dictionary1)
{
  dictionary2.Add(val.Key, val.Value);
}

WORKING FIDDLE

這應該為你做

using System;
using System.Linq;
using System.Collections.Generic;


namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>() { {"Name", "xyz" }, {"3", "39"}};
            Dictionary<string, string> copy = new Dictionary<string, string>();
            dic.Copy(copy);
            copy.ToList().ForEach(c => Console.Write("\n" + c));
            Console.ReadLine();
        }
    }

    public static class Ext
    {
        public static void Copy(this Dictionary<string, string> dic, Dictionary<string, string> other)
        {
            dic.ToList().ForEach(d => other.Add(d.Key, d.Value));
        } 
    }
}

我確定之前已經回答過

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM