你好开发人员我想从数组中的某些对象中获取随机数据,但是当我想显示它时显示对象 [object],而不是显示来自对象的文本,我尝试了很多方法但没有任何解决方案?非常感谢帮助我的人
let bill = [
{
name : "Sandra",
price : "50$",
payment : "visa",
cardnumber:"1234 5678 9012 3456"
},
{
name : "Johnson",
price : "200$",
payment : "master",
cardnumber:"1234 5678 9012 3456"
},
]
let get = document.querySelector(".get");
let first = document.querySelector(".first");
let second = document.querySelector(".second");
let third = document.querySelector(".third");
let fourth= document.querySelector(".fourth");
get.addEventListener("click" , ()=> {
let text= bill[Math.floor(Math.random()* bill.length)];
first.innerHTML = text;
second.innerHTML = text;
third.innerHTML = text;
fourth.innerHTML = text;
})
body {
font-family:"Lato",sans-serif;
display:flex;
align-items:center;
justify-content:center;
flex-direction:column;
}
<body>
<h1>
Get latest invoice
</h1>
<button class="get">Get</button>
<table >
<tr>
<th>Name</th>
<th>Price</th>
<th>Payment</th>
<th>Card Number</th>
</tr>
<tr>
<td class="first"></td>
<td class="second "></td>
<td class="third"></td>
<td class="fourth"></td>
</tr>
</table>
</body>
它是 return [object] 因为 text 变量是一个对象,所以如果你想获得名字,你应该通过调用它的键来获得,比如 first.innerHtml = text.name (获取名字)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
body {
font-family: "Lato", sans-serif;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
</style>
<body>
<h1>Get latest invoice</h1>
<button class="get">Get</button>
<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Payment</th>
<th>Card Number</th>
</tr>
<tr>
<td class="first"></td>
<td class="second"></td>
<td class="third"></td>
<td class="fourth"></td>
</tr>
</table>
</body>
<script>
let bill = [
{
name : "Sandra",
price : "50$",
payment : "visa",
cardnumber:"1234 5678 9012 3456"
},
{
name : "Johnson",
price : "200$",
payment : "master",
cardnumber:"1234 5678 9012 3456"
},
]
let get = document.querySelector(".get");
let first = document.querySelector(".first");
let second = document.querySelector(".second");
let third = document.querySelector(".third");
let fourth= document.querySelector(".fourth");
get.addEventListener("click" , ()=> {
let text= bill[Math.floor(Math.random()* bill.length)];
console.log(text);
first.innerHTML = text.name;
second.innerHTML = text.name;
third.innerHTML = text.name;
fourth.innerHTML = text.name;
})
</script>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句