在JavaScript中等同两个对象。在更改一个,第二个自动更改

时间:2015-04-03 12:39:56

标签: javascript

我试图在for循环中使用哈希映射: 但是在重置第二个对象时,它会自动更改哈希映射中前一个键的Map值。请帮我防止这种情况。 代码:

    for (i = 0; i < tds.length; ++i) {
        tdtext = $(tds[i]).text();
        //iIndex = tdtext.indexOf('Success')>-1 ? tdtext.indexOf('Success') : tdtext.indexOf('Failed');
        iIndex = 8;
        key = tdtext.substring(0, iIndex);
        outcome = tdtext.substring(iIndex);
        //var sCombine = sNum1 + sNum2;
        console.log(iIndex, outcome);

        //Reset oCount for next use
        var oCount = Object.create(null);
        oCount.total = 0; oCount.success = 0;//2. Here it is changing the vlaues assigned in step 1

        //Case 1: If map already has key
        if (map.hasOwnProperty(key)) {
            //var ob = map.get(key);
            if (outcome === "Success")
            map[key].success++;
            map[key].total++;
        }

        //Case 2: If map doesn't have key
        else {
            if (outcome === "Success")
                oCount.success++;
            //If outcome is failure or success irrespective of that we increase the total count
            oCount.total++;
            map[key] = oCount;//1. Here I am Equating 2 Objects
        }

1 个答案:

答案 0 :(得分:1)

我试图了解并创建了示例,并且它有效。地图中没有值被替换。

http://jsfiddle.net/wasikuss/nrun0dty/

var oCount = Object.create(null);也可以替换为var oCount = {};