我有一个声明:

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
    ) //console.log expanded for readability
    }
}


为什么不记录完整的字符串,而只求值sep

最佳答案

因为您没有将if行包装在括号中,而是将其之前的所有字符串作为条件进行处理。

尝试这个...

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

10-06 04:28