开发者

Ternary operator always evaluating to true part

I have a statement:

var sep = '  |  ';
var r = '';
for (var i = 0; i < menuItems.length; i++) {
    r += function(menuObject) {
    console.log(menuObject);
    console.log(
        '<a class="" href="' + 
        menuObject.url + '">' + menuObject.name + '</a>' + 
        (i < menuItems.length - 1) ? sep : ""); //logs the contents of sep
    ) 开发者_JAVA百科//console.log expanded for readability
    }
}

Why is it not logging the full string, and instead only evaluating to sep?


Because you are not wrapping your if line in parenthesis and it is process all of the string before it as the condition.

Try this...

var sep = '&nbsp;&nbsp;|&nbsp;&nbsp;';
        var r = '';
        for (var i=0;i<menuItems.length; i++) {
            r += function (menuObject) {
            console.log(menuObject);
            console.log(
                '<a class="" href="' + 
                menuObject.url + '">' + menuObject.name + '</a>'+ 
                ((i <menuItems.length-1 ) ? sep : "")); //logs the contents of sep
            }
       }


The issue is operator precedence.

console.log(
            ('<a class="" href="' + 
            menuObject.url + '">' + menuObject.name + '</a>'+ 
            (i <menuItems.length-1 )) ? sep : ""); 

is being executed (mind the extra parenthesis I added). When using the ternary operator (which has only little to do with if clauses btw.) you should always use parenthesis like here:

console.log(
            '<a class="" href="' + 
            menuObject.url + '">' + menuObject.name + '</a>'+ 
            ((i <menuItems.length-1 ) ? sep : "")); 


Operator precedence. Put your expression before ? in parentheses:

console.log(
        ('<a class="" href="' + 
        menuObject.url + '">' + menuObject.name + '</a>'+ 
        (i <menuItems.length-1 )) ? sep : "");
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜