Javascript array.prototype.map()需要为NFL团队计算赢、输、平
我正在试验.map()数组方法,但找不到在对象中生成“wlt”列的正确语法。“wlt”代表胜利、失败或平局 目前,我正在使用以下代码生成“wlt”列:Javascript array.prototype.map()需要为NFL团队计算赢、输、平,javascript,array.prototype.map,Javascript,Array.prototype.map,我正在试验.map()数组方法,但找不到在对象中生成“wlt”列的正确语法。“wlt”代表胜利、失败或平局 目前,我正在使用以下代码生成“wlt”列: const scores = philadephiaEaglesScores.map(function(item){ const obj = { "weekNumber": item.weekNumber, "name": item.ourName, "oppName": item.oppName,
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
在第一个代码示例中,我希望将其提升到下一个级别,并实际生成一个字符串值,即win、Lost或Tie
let winLossTie = philadephiaEaglesScores.map(item => {
if (item.ourScore > item.oppScore) {
return "W";
} if (item.ourScore < item.oppScore) {
return "L";
} else {return "T"}
});
我可以使用下面的代码使其工作,但无法使第二个代码示例在第一个代码示例中工作
let winLossTie = philadephiaEaglesScores.map(item => {
if (item.ourScore > item.oppScore) {
return "W";
} if (item.ourScore < item.oppScore) {
return "L";
} else {return "T"}
});
可以对if/else语句使用三元运算符replace 看起来是这样的:
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 ? "W" : item.ourScore < item.oppScore ? "L" : "T"
}
return obj;
});
const scores=PhiladephiaeglesScores.map(功能(项目){
常量对象={
“周号”:item.weekNumber,
“名称”:item.ourName,
“oppName”:item.oppName,
“ourScore”:item.ourScore,
“oppScore”:item.oppScore,
“wlt”:item.ourScore>item.oppScore?“W”:item.ourScore
您可能希望将三元数分隔为语句/表达式/函数,以获得更清晰的代码。在第一个代码中,更改:
"wlt": item.ourScore - item.oppScore
致:
在迭代整个数组时,不能实际使用第二个函数。如果该函数将数组中的一个对象作为参数,并且只返回仅适用于该对象的字符串,则该函数将起作用。然后您可以这样调用该函数:
"wlt": winLossTie(item)
因此,明确地说,该功能需要更改为以下内容:
function winLossTie(item) {
if (item.ourScore > item.oppScore) {
return "W";
} if (item.ourScore < item.oppScore) {
return "L";
} else {
return "T"
}
});
函数winLossTie(项){
如果(item.ourScore>item.oppScore){
返回“W”;
}如果(item.ourScore
但是使用Math.sign
(返回-1、0或1)的快捷方式使其足够短,根本不需要单独的函数
function winLossTie(item) {
if (item.ourScore > item.oppScore) {
return "W";
} if (item.ourScore < item.oppScore) {
return "L";
} else {
return "T"
}
});