如何使用 document.getElementById("abc").innerHTML DOM 以字符串格式显示 JavaScript 对象的内容?

How do I display the content of a JavaScript object in a string format using document.getElementById("abc").innerHTML DOM?

想在屏幕上而不是在一个控制台上显示我的输出。

var str = lowerString.split(" ");
var count = {};
str.forEach(function(s){
    count[s] ? count[s]++ : count[s] = 1;
});
console.log(count); 

const lowerString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lacus purus, volutpat ac arcu sit amet, cursus dapibus odio".split(' ');

const wordCounter = word => lowerString.reduce((acc, curr) => {
  acc[curr] = acc[curr] ? acc[curr] + 1 : 1
  return acc
}, {})[word]

const wordToCount = 'sit';
const wordOccurrences = wordCounter(wordToCount);

document.querySelector('#result').innerHTML = `${wordOccurrences} occurrences found for the word "${wordToCount}"`
<h2 id="result"></h2>

您可以使用 reducer 创建包含字符串中所有出现的字典,然后您可以使用 innerHTML 在屏幕上打印

    var j = { "my": 1, "name": 1, "is": 1, "gauri": 2, "and": 2, "narayan": 1, "srijan": 1 };
    var s = "";
    for (var k in j) {
      s += k + ":" + j[k] + ',';
    }
    document.getElementById('app').innerHTML = s;

你可以自己替换最后一个','

<!DOCTYPE html>
<html>
<body>

 

<p id="demo"></p>

<script>
var lowerString="twst";
var str = lowerString.split(" ");
var count = {};
str.forEach(function(s){
    count[s] ? count[s]++ : count[s] = 1;
});

document.getElementById("demo").innerHTML = JSON.stringify(count);
</script>

</body>
</html>