我正在使用javascript在一个表中显示我的数据,该表显示了名称,性别,外观和年龄列。
对于“外观”列,我编写了一个脚本,因此,如果性别是男性,则该列应将Looks的值显示为“英俊”,如果性别是女性,则该列应将Looks的值显示为“美丽”。在值中。
但这对男性和女性都只显示“英俊”。
以下是我的代码:
var myObj = [{name: "Taimoor", sex: "male", age: "Thirty One"},{name:
"Nida", sex: "female", age: "Twenty Nine"}];
var table = "<tr><td>Name</td><td>Sex</td><td>Looks</td><td>Age</td>
</tr>";
function myLooks() {
for (ii in myObj) {
var looks = "";
if (myObj[ii].sex == "male") {looks = "handsome"}
else {looks = "beautiful"};
return looks;
}
}
for (i=0; i <myObj.length; i++) {
table += "<tr><td>" + myObj[i].name + "</td><td>" + myObj[i].sex + "
</td><td>" + myLooks() + "</td><td>" + myObj[i].age + "</td></tr>"
document.getElementById("demo").innerHTML = table;
答案 0 :(得分:1)
您不需要循环,可以将sex传递给函数并获取返回的正确字符串:-
var myObj = [{name: "Taimoor", sex: "male", age: "Thirty One"},{name:
"Nida", sex: "female", age: "Twenty Nine"}];
function myLooks(sex) {
if (sex == "male") {
return "handsome"
}
else {
return "beautiful"
}
}
for (i = 0; i < myObj.length; i++) {
console.log(myObj[i].name, myObj[i].sex, myLooks(myObj[i].sex), myObj[i].age);
}
答案 1 :(得分:0)
首先,myObj
是一个数组,并且您正在使用for/in
循环。 for/in
loops should not be used with Arrays,因为它们迭代了Array对象的所有属性,而不仅仅是索引。要简单地迭代数组,可以使用常规计数循环.forEach()
或for/of
。
您还可以第二次循环并多次调用函数,而您只需运行一次函数并循环遍历一次数组即可。
var myObj = [
{name: "Taimoor", sex: "male", age: "Thirty One"},
{name: "Nida", sex: "female", age: "Twenty Nine"}
];
var headerRow = "<tr><td>Name</td><td>Sex</td><td>Looks</td><td>Age</td></tr>";
var table = document.getElementById("demo");
table.innerHTML = headerRow;
function myLooks() {
var newRow = "";
var looks = "";
myObj.forEach(function(obj) {
if (obj.sex == "male") {
looks = "handsome";
} else {
looks = "beautiful"
};
newRow = "<tr><td>" + obj.name + "</td><td>" + obj.sex +
"</td><td>" + looks + "</td><td>" + obj.age + "</td></tr>"
table.innerHTML += newRow;
});
}
myLooks();
table, td { border:1px solid #e0e0e0;}
<table id="demo"></table>
答案 2 :(得分:0)
当前,您的myLooks
函数基于looks
数组中的第一项设置myObj
变量,然后返回。取而代之的是,您可以将要确定外观的值作为参数传递给函数,下面是一个示例:
var myObj = [{
name: "Taimoor",
sex: "male",
age: "Thirty One"
}, {
name: "Nida",
sex: "female",
age: "Twenty Nine"
}];
var table = "<tr><td>Name</td><td>Sex</td><td>Looks</td><td>Age</td> </tr>";
function myLooks(obj) {
var looks = "";
if (obj.sex == "male") {
looks = "handsome"
} else {
looks = "beautiful"
};
return looks;
}
for (i = 0; i < myObj.length; i++) {
table += ("<tr><td>" + myObj[i].name + "</td><td>" + myObj[i].sex + " </td><td>" + myLooks(myObj[i]) + "</td> <td> " + myObj[i].age + " </td></tr > ");
}
document.getElementById("demo").innerHTML = table;
<table id="demo"></table>