Heim  >  Fragen und Antworten  >  Hauptteil

javascript - jslint对于三元操作符的检查问题

function abc(a) {
    'use strict';
    a = (a !== undefined) ? a : 'GET';
}

为什么会抛出如下异常?(不是错误,是不符合规范JSLint)

Expected '?' at column 8, not column 26.
    a = (a !== undefined) ? a : 'GET';
line 2 column 30Expected ':' at column 8, not column 30.
    a = (a !== undefined) ? a : 'GET';
PHP中文网PHP中文网2750 Tage vor272

Antworte allen(3)Ich werde antworten

  • ringa_lee

    ringa_lee2017-04-10 15:39:07

    JSLint对空白符(缩进)有明确规定

    The ternary operator can be visually confusing, so ? question mark and : colon always begin a line and increase the indentation by 4 spaces.

    三元操作符的?:要换新行并增加4个空格的缩进。所以它要求?在第8列,:同理。

    所以正确的写法是:

    javascriptfunction abc(a) {
        'use strict';
        a = (a !== undefined)
            ? a
            : 'GET';
    }
    

    Antwort
    0
  • 阿神

    阿神2017-04-10 15:39:07

    试了下,没有错啊,楼主再检查下呢

    Antwort
    0
  • 高洛峰

    高洛峰2017-04-10 15:39:07

    试了下,没有报错。
    楼主的初衷如果是想判断a是否存在,不存在设置默认值,可以这样写

    function abc(a){
        if (a == null) {
            a = 'GET';
        }
    }
    

    这样可读性会好很多。

    Antwort
    0
  • StornierenAntwort