【发布时间】:2020-02-06 15:56:04
【问题描述】:
我正在试验 .map() 数组方法,但找不到在我的对象中生成“wlt”列的正确语法。 “wlt” 代表 Win、Loss 或 Tie。
目前我正在使用以下代码生成“wlt”列:
const scores = philadephiaEaglesScores.map(function(item){
const obj = {
"weekNumber": item.weekNumber,
"name": item.ourName,
"oppName": item.oppName,
"ourScore": item.ourScore,
"oppScore": item.oppScore,
"wlt": item.ourScore - item.oppScore
}
return obj;
});
这确实有效,如果我们赢了比赛,给我一个正数,如果我们输了比赛,则给我一个负数,如果比赛是平局,则给我 0。
我想更进一步,在第一个代码示例中实际生成一个字符串值 Won、Lost 或 Tie。
我可以使用以下代码使其工作,但无法让第二个代码示例在第一个代码示例中工作。
let winLossTie = philadephiaEaglesScores.map(item => {
if (item.ourScore > item.oppScore) {
return "W";
} if (item.ourScore < item.oppScore) {
return "L";
} else {return "T"}
});
My JSON data is listed below:
const philadephiaEaglesScores = [
{"weekNumber": "1","ourName": "Philadephia Eagles", "oppName": "Redskins", "ourScore": "32",
"oppScore": "27", "location": ""},
{"weekNumber": "2","ourName": "Philadephia Eagles", "oppName": "Falcons", "ourScore": "20",
"oppScore": "27", "location": ""},
{"weekNumber": "3","ourName": "Philadephia Eagles", "oppName": "Lions", "ourScore": "24", "oppScore":
"27", "location": ""},
{"weekNumber": "4","ourName": "Philadephia Eagles", "oppName": "Packers", "ourScore": "34",
"oppScore": "27", "location": ""},
{"weekNumber": "5","ourName": "Philadephia Eagles", "oppName": "Packers", "ourScore": "31",
"oppScore": "6", "location": ""},
{"weekNumber": "6","ourName": "Philadephia Eagles", "oppName": "Vikings", "ourScore": "20",
"oppScore": "38", "location": ""},
{"weekNumber": "7","ourName": "Philadephia Eagles", "oppName": "Cowboys", "ourScore": "10",
"oppScore": "37", "location": ""},
{"weekNumber": "8","ourName": "Philadephia Eagles", "oppName": "Bills", "ourScore": "31", "oppScore":
"13", "location": ""},
{"weekNumber": "9","ourName": "Philadephia Eagles", "oppName": "Bears", "ourScore": "22", "oppScore":
"14", "location": ""},
{"weekNumber": "11","ourName": "Philadephia Eagles", "oppName": "Patriots", "ourScore": "10",
"oppScore": "17", "location": ""},
{"weekNumber": "12","ourName": "Philadephia Eagles", "oppName": "Seahawks", "ourScore": "9",
"oppScore": "17", "location": ""},
{"weekNumber": "13","ourName": "Philadephia Eagles", "oppName": "Dolphins", "ourScore": "31",
"oppScore": "37", "location": ""},
{"weekNumber": "14","ourName": "Philadephia Eagles", "oppName": "Giants", "ourScore": "23",
"oppScore": "17", "location": ""},
{"weekNumber": "15","ourName": "Philadephia Eagles", "oppName": "Redskins", "ourScore": "37",
"oppScore": "27", "location": ""},
{"weekNumber": "16","ourName": "Philadephia Eagles", "oppName": "Cowboys", "ourScore": "17",
"oppScore": "9", "location": ""},
{"weekNumber": "17","ourName": "Philadephia Eagles", "oppName": "Giants", "ourScore": "37",
"oppScore": "17", "location": ""},
];
【问题讨论】:
标签: javascript array.prototype.map