三元运算符检查多个字符串

时间:2016-05-13 18:08:59

标签: javascript angularjs

我有一段代码,我在检查值是null还是turnedoff,然后在左侧的变量中加上blank space。但由于某种原因,turnedoff没有被取代。我做错了什么?

JS:

$scope.ModelAux ={
  ssclientID: sessionStorage.clientId === ('null' || 'turnedoff') ? '' : sessionStorage.clientId
};

alert($scope.ModelAux.ssclientID);

CSHTML:

<input type="text" name="clientID" class="form-control input-md" ng-model="ModelAux.ssclientID" required/>

3 个答案:

答案 0 :(得分:6)

sessionStorage.clientId === ('null' || 'turnedoff') ?

应该是

sessionStorage.clientId === 'null' || sessionStorage.clientId ===  'turnedoff' ?

,因为

'null' || 'turnedoff'

始终为'null',并且不会检查值是否为'turnedoff'

答案 1 :(得分:2)

@Nina Scholz说的是正确的。如果你想获得更多的简洁,你也可以这样做:

['null','turnedoff'].indexOf(sessionStorage.clientId) >= 0 ? '', sessionStorage.clientId;

答案 2 :(得分:1)

尝试以下

(!sessionStorage.clientId || sessionStorage.clientId ===  'turnedoff') ? ''