在JavaScript中相等两个对象.在更改一时,秒会自动更改

Equating two Objects in JavaScript. On Changing one, second automatically changes

本文关键字:一时 对象 JavaScript 两个      更新时间:2023-09-26

我正在尝试在for循环中使用哈希映射:但是在重置第二个对象时,它会自动更改哈希映射中上一个Key的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
        }

我试着理解并创建了示例,它很有效。映射中没有任何值被替换。

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

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