首页 > jslint对于三元操作符的检查问题

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';

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


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';
}

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

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

这样可读性会好很多。

【热门文章】
【热门文章】