我正在尝试在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
        }

最佳答案

我试图理解,并创建了示例,并且可以正常工作。映射中的任何值均不会替换。

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

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

09-27 06:52