我有一个简单的应用程序,可以计算数组内部的重复数字。 用户通过提示输入数字(即2,1,2,2)。
当我想通过document.write()函数输出结果(这是一个对象)时,我得到: [object Object]
当我通过控制台输出时,我得到了我期望的结果: 对象{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);
});
答案 0 :(得分:1)
使用JSON.stringify(counts)
序列化您的对象,然后您可以在HTML
document.write(
"<h1>Enter numbers when prompted!</h1>" +
"<p>You entered following numbers:</p>" + n + "<br/>" +
"<p>The occurence is as follows:</p>" + JSON.stringify(counts));
});
答案 1 :(得分:1)
你不能。 HTML
无法解析objects
。但是,您可以将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));
});
&#13;
<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>
&#13;
答案 2 :(得分:0)
您可以使用JSON.stringify(counts)
$(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);
});