如何从JavaScript控制台输出中的“名称”和“计数”中消除双引号?

问题描述

我无法切换输入

[“苹果”,“香蕉”,“胡萝卜”,“榴莲”,“茄子”,“苹果”,“胡萝卜”] 进入正确的输出

[{名称:“ Apple”,计数:2},{名称:“香蕉”,计数:1},{名称:“胡萝卜”,计数:2},{名称:“榴莲”,计数:1 },{名称:“茄子”,计数:1}], 我在输出错误时遇到了麻烦:

[{“ name”:“ Apple”,“ count”:2},{“ name”:“ Banana”,“ count”:1},{“ name”:“ Carrot”,“ count”:2 },{“ name”:“ Durian”,“ count”:1},{“ name”:“ eggplant”,“ count”:1}]。 如何获得正确的输出

[{名称:“ Apple”,计数:2},{名称:“香蕉”,计数:1},{名称:“胡萝卜”,计数:2},{名称:“榴莲”,计数:1 },{名称:“茄子”,计数:1}] 使用console.log()方法

    <html>
    <body>
    <script>
    var input = ["apple","banana","carrot","durian","eggplant","apple","carrot"];
    
    var A = 0;//to count the number of apples
    var B = 0;//to count the number of bananas
    var C = 0;//to count the number of carrots
    var D = 0;//to count the number of durians
    var E = 0; //to count the number of eggplants

     for (var i = 0; i < input.length; i++)
      {
         if (input[i] == "apple")
         {   
           A += 1;  
          }
         if (input[i] == "banana")
         {   
           B += 1;  
          }
         if (input[i] == "carrot")
         {   
           C += 1;  
          }
         if (input[i] == "durian")
         {   
           D += 1;  
         }
         if (input[i] == "eggplant")
         {   
           E += 1;  
         }
       }            

    let x1 = { name: 'Apple',count: A };
    let x2 = { name: 'Banana',count: B };
    let x3 = { name: 'Carrot',count: C };
    let x4 = { name: 'Durian',count: D };
    let x5 = { name: 'eggplant',count: E };

   var output = [];
   output.push(x1);
   output.push(x2);
   output.push(x3);
   output.push(x4);
   output.push(x5);

   console.log("output = ",output);
   document.getElementById('output').innerHTML = JSON.stringify(output);

   </script>
   </body>
   </html>

解决方法

您可以使用如下正则表达式:

var yourStringifiedResult = "[{\"name\":\"Apple\",\"count\":2},{\"name\":\"Banana\",\"count\":1},{\"name\":\"Carrot\",{\"name\":\"Durian\",{\"name\":\"Eggplant\",\"count\":1}]";

yourStringifiedResult = yourStringifiedResult.replace(/"(\w+)"\s*:/g,'$1:');
console.log(yourStringifiedResult);

工作示例:

var yourStringifiedResult = "[{\"name\":\"Apple\",'$1:');
console.log(yourStringifiedResult);

,

只需在推送数组中的所有对象之后添加此行:

let outputInString = "";

for (let fruit of input) outputInString += "Name: " + fruit.name + ",Count: " + fruit.count + ",";

document.getElementById('output').innerHTML = outputInString;