代码之家  ›  专栏  ›  技术社区  ›  Fred Hors

Javascript,不带三元运算符的字符串连接

  •  3
  • Fred Hors  · 技术社区  · 8 年前

    我通常用这个:

    myVar = "myString is" + 1 === 1 ? " really true" : " false, I think";
    

    也许我只需要真实的部分,比如说:

    myVar = "myString is" + 1 === 1 ? " really true" : "";
    

    我不喜欢这部分: : ""

    有没有办法使用下面这样的东西?

    myVar = "myString is" + 1 === 1 && " really true";
    

    它是有效的,但是当它写为false时会有一个问题 "false" !

    6 回复  |  直到 8 年前
        1
  •  1
  •   sbrass    8 年前

    var myVar = 'myString is';
    if (1===1){myVar+=' really true';}
    

    我认为这比一行布尔测试更具可读性

        2
  •  0
  •   Mosè Raguzzini    8 年前

    myVar=“我的字符串是”+myHelper(…myParams);

        3
  •  0
  •   Sushanth --    8 年前

    你可以用 ||

    myVar = (1 === 1 && "myString is really true") || "";
    
        4
  •  0
  •   ionizer    8 年前

    包装 1 === 1 && " really true" () 再加上 || '' 像下面这样(也用括号括起来),或者可以使用模板文本来节省您键入这些文本的时间 + s

    let myString = "myString is" + ((1 === 1 && " really true") || '');
    let myFalseString = "myString is" + ((1 === 0 && " really true") || '');
    let onlyFalse = "myString is" + 1 === 1 && " really true";
    let myTL = `myString is ${(1 === 1 && "really true") || ''}`;
    
    console.log('My String:', myString);
    console.log('False String:', myFalseString);
    console.log('Only false:', onlyFalse);
    console.log('My Template Literal:', myTL);

    看起来比有多余的更糟 : "" 尽管如此,我还是建议这样做:

    myVar = "myString is" + 1 === 1 ? " really true" : "";
    
        5
  •  0
  •   keja    8 年前

    : '' 但据我所知 : ''

    console.log( ["my string is", 1 === 1 && "really true"].filter(Boolean).join(" ") );
    console.log( ["my string is", 1 === 2 && "really true"].filter(Boolean).join(" ") );

    : ''

    function concat(){
      let str = "";
      for(let s of arguments){
        str += s ? s : '';
      }
      return str;
    }
    
    console.log( concat("my string is", 1 === 1 && "really true") );
    console.log( concat("my string is", 1 === 2 && "really true") );
        6
  •  0
  •   Leonardo Diehl    8 年前

    分析三元运算符,我们得出如下结论:

    // Example: 1 === 1 ? ' is really true' : ''
    if (1 === 1) {
        return ' is really true';
    } else {
        return '';
    }
    

    if (1 === 1) {
        myVar += 'is really true';
    }
    

    使用逻辑运算符内联的最佳解决方案是三元运算符本身。它的“false”部分作为空字符串“”不是问题。但如果您真的对此感到恼火,您可以创建一个函数并使用如下模板文本:

    function myFunction(evaluation) {
        if (evaluation) {
            return ' really true';
        }
        return '';
    }
    
    let myVar = `My String is ${myFunction(1 === 1)}`;