什么是 ?在JQUERY

kak*_*aka 0 jquery

我有以下代码,我试图理解它:

labels: {
   formatter: function () {
    return (this.value > 0 ? ' + ' : '') + this.value + '%';
                        }
        },
Run Code Online (Sandbox Code Playgroud)

但我不明白是什么?意思?有人能解释一下吗?我会很感激.

tbr*_*n89 5

?条件三元运算符,你可以用这样的if语句表达相同的:

labels: {
    formatter: function () {
        if (this.value > 0) {
            return ' + ' + this.value + '%';
        } else {
            return '' + this.value + '%';
        }
    }
},
Run Code Online (Sandbox Code Playgroud)

它的工作方式如下:如果条件为真,则执行第一个参数,如果不是第二个参数.

CONDITION ? EXPRESSION_ON_TRUE : EXPRESSION_ON_FALSE
Run Code Online (Sandbox Code Playgroud)

如何使用此运算符的其他一些示例:

// assign 'a' or 'b' to myVariable depending on the condition
var myVariable = condition ? 'a' : 'b';

// call functionA or functionB depending on the condition
condition ? functionA() : functionB();

// you can also chain them (but keep in mind this can become very complicated)
var myVariable = cond ? (condA ? 'a' : 'b') : (condB ? 'c' : 'd')
Run Code Online (Sandbox Code Playgroud)

此外,这个运算符没有什么特别的,你只能使用jQuery库,你也可以使用纯JavaScript.