我有一个简单的应用程序,可以计算数组内的重复数字。 用户通过提示输入数字(即 2、1、2、2)。
当我想通过 document.write() 函数输出结果(它是一个对象)时,我得到: [对象对象]
当我通过控制台输出它时,我得到了我期望的结果: 对象 {2: 3, 1:1}
下面是html和js,Plunkr可以找here
我希望对象的结果写在页面上...
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- JAVASCRIPT AND JQUERY STUFF -->
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">
</script>
<script src="number-list.js"></script>
</head>
<body>
<h1>Enter numbers when prompted!</h1>
<p>Here are the numbers entered on the left and frequency of occurence on the right.</p>
</body>
</html>
JavaScript
$(document).ready(function(){
var n = prompt("Enter your numbers").split(",");
console.log(n);
var counts = {};
n.forEach(function(x){
counts[x] = (counts[x] || 0) +1;
});
console.log(counts);
document.write(
"<h1>Enter numbers when prompted!</h1>" +
"<p>You entered following numbers:</p>" + n + "<br/>" +
"<p>The occurence is as follows:</p>" + counts);
});
最佳答案
你不能。 HTML
无法解析对象
。但是,您可以将 object
转换为 string
$(document).ready(function(){
var n = prompt("Enter your numbers").split(",");
console.log(n);
var counts = {};
n.forEach(function(x){
counts[x] = (counts[x] || 0) +1;
});
console.log(counts);
document.write(
"<h1>Enter numbers when prompted!</h1>" +
"<p>You entered following numbers:</p>" + JSON.stringify(n) + "<br/>" +
"<p>The occurence is as follows:</p>" + JSON.stringify(counts));
});
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">
</script>
<script src="number-list.js"></script>
<body>
<h1>Enter numbers when prompted!</h1>
<p>Here are the numbers entered on the left and frequency of occurence on the right.</p>
<div id="content"></div>
关于javascript - 如何使用 document.write() 将对象写入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46036154/