需要扩展JavaScript语句速记

时间:2011-08-17 21:18:48

标签: javascript

我有这样的声明:

pn = r.notFound == "true" ? "Not currently assigned" : "Currently assigned to VPMO " + r.currentAssignment;

我需要为“undefined”添加一个条件,然后为它添加一个值。它基本上需要阅读类似......

r.notFound == "undefined" then “Already assigned to this project”
else if r.notFound == “true” then “Not currently assigned”
else
“Currently assigned to VPMO “ + r.currentAssignment;

2 个答案:

答案 0 :(得分:2)

var pn;

if (r.notFound == 'undefined') { // be aware that this checks for STRING undefined
  pn = 'Already assigned to this project';
} else if (r.notFound == 'true') { // be aware that this checks for STRING true
  pn = 'Not currently assigned';
} else {
  pn = 'Currently assigned to VPMO ' + r.currentAssignment;
}

修改

如果要检查变量是否已定义,请使用:

if (typeof r.notFound === 'undefined') 

答案 1 :(得分:0)

您可以使用多个嵌套的三元运算符:

r.notFound == "undefined" ? 
    "Already assigned to this project" :
    (r.notFound == "true" ? "Not currently assigned" : "Currently assigned to VPMO " + r.currentAssignment)