在js中显示数组对象



我有一个数组对象

我想在排序之前和之后显示它。

我的代码是:

const obj = [
{ name: "ahmad", family: "mahdavi", city: "esf", score: 10 },
{ name: "ali", family: "Ahmadi", city: "ahv", score: 5 },
{ name: "reza", family: "rezaei", city: "tehran", score: 3 },
{ name: "mohammad", family: "kiani", city: "shiraz", score: 19 }
];
let txt = "";
document.getElementById("p1").innerHTML = dis();
obj.sort(
function (a, b) {
return a.score - b.score;
}
)
document.getElementById("p2").innerHTML = dis();

function dis() {
obj.forEach(element => {
txt += element.name + " " + element.family + " " + element.city + " " + element.score + "<br>";
})
return txt;
}
<p id="p1"></p>
<p id="p2"></p>

它应该显示2次数据,但是它显示了3次。为什么?

发生这种情况是因为您的txt变量是全局的并且不断收集数据。您应该将其设置为一个局部变量,以便每次调用dis:

时都从头开始。

const obj = [
{ name: "ahmad", family: "mahdavi", city: "kian", score: 10 },
{ name: "ali", family: "Ahmadi", city: "Shahrekord", score: 5 },
{ name: "reza", family: "rezaei", city: "tehran", score: 3 },
{ name: "mohammad", family: "kiani", city: "shiraz", score: 19 }
];
document.getElementById("p1").innerHTML = dis();
obj.sort(
function (a, b) {
return a.score - b.score;
}
)
document.getElementById("p2").innerHTML = dis();

function dis() {
var txt = ""; // <---
obj.forEach(element => {
txt += element.name + " " + element.family + " " + element.city + " " + element.score + "<br>";
})
return txt;
}
<p id="p1"></p>
<p id="p2"></p>

相关内容

  • 没有找到相关文章

最新更新