简写if语句 - 意外的令牌;

Bat*_*man 0 javascript arrays if-statement

我在下面有这个函数,告诉我用户是否在基于用户和组数组的特定组中.现在它正在生成一个表明真或假的表.我想它只是标记一个"X"如果是真的和" - "如果是假的.

这是功能:

function processAll(){
    for(var i=0; i<users.length; i++){
        userGroupTable[users[i]] = {};
        var userGroups = parseGroupCollFromUser(users[i]);
        for(var j=0; j<groups.length; j++){
            //if the array userGroups contains the current group, the value must be true
            userGroupTable[users[i]][groups[j]] = userGroups.indexOf(groups[j]) > -1; *think this line is whats giving the result
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试将线路更改为:

userGroupTable[users[i]][groups[j]] = (userGroups.indexOf(groups[j]) > -1) ? " X " | " - ";
Run Code Online (Sandbox Code Playgroud)

但我明白了 Unexpected token ;

Elo*_*han 12

你必须使用:而不是|.

这是ternary operator,它看起来像这样

$a === $b ? true : false;
Run Code Online (Sandbox Code Playgroud)

  • 敏捷的事情......容易的声誉点`:p` (2认同)