[英]How do you get rid of double quotes from "name" and "count" from the console output in JavaScript?
我在轉動輸入時遇到問題:
["apple", "banana", "carrot", "durian", "eggplant", "apple", "carrot"] 右轉output:
[{ name: "Apple", count: 2 }, { name: "Banana", count: 1 }, { name: "Carrot", count: 2 }, { name: "Durian", count: 1 }, { } name: "Eggplant", count: 1 }], 我這里遇到錯誤 output:
[{"name":"Apple","count":2},{"name":"Banana","count":1},{"name":"Carrot","count":2},{ “名稱”:“榴蓮”,“計數”:1},{“名稱”:“茄子”,“計數”:1}]。 我怎樣才能擁有正確的output:
[{ name: "Apple", count: 2 }, { name: "Banana", count: 1 }, { name: "Carrot", count: 2 }, { name: "Durian", count: 1 }, { } name: "Eggplant", count: 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\",\"count\":2},{\"name\":\"Durian\",\"count\":1},{\"name\":\"Eggplant\",\"count\":1}]";
yourStringifiedResult = yourStringifiedResult.replace(/"(\w+)"\s*:/g, '$1:');
console.log(yourStringifiedResult);
工作樣本:
var yourStringifiedResult = "[{\"name\":\"Apple\",\"count\":2},{\"name\":\"Banana\",\"count\":1},{\"name\":\"Carrot\",\"count\":2},{\"name\":\"Durian\",\"count\":1},{\"name\":\"Eggplant\",\"count\":1}]"; yourStringifiedResult = yourStringifiedResult.replace(/"(\w+)"\s*:/g, '$1:'); console.log(yourStringifiedResult);
只需在推送數組中的所有對象后添加此行:
let outputInString = "";
for (let fruit of input) outputInString += "Name: " + fruit.name + ", Count: " + fruit.count + ", ";
document.getElementById('output').innerHTML = outputInString;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.