代码之家  ›  专栏  ›  技术社区  ›  VoteyDisciple

串接中的第一个还是第二个字符串?

  •  26
  • VoteyDisciple  · 技术社区  · 6 年前

    在javascript中,这两个选项之间是否存在语义差异?

    foo.bar + ''
    

    …还有…

    '' + foo.bar
    

    我本以为后者会更可靠地将结果强制转换为字符串,但我找不到对此的任何讨论(在大量谷歌搜索之后),也找不到任何看起来重要的例子。

    5 回复  |  直到 6 年前
        1
  •  13
  •   Rick Gal Koren    6 年前

    @Zohaib Ijaz

    var values = [
      undefined,
      null,
      false,
      true,
      0,
      -1,
      1,
      NaN,
      Infinity,
      '',
      '123',
      'abc123',
      '123abc',
      [],
      [0],
      [1],
      {},
      {a: 1},
      function(){}   
    ];
    var foo = {bar: null};
    
    values.forEach(function(value) {
      foo.bar = value;
      
      console.log("foo.bar + '':", foo.bar + '');
      console.log("'' + foo.bar:", '' + foo.bar);
    });

    @ibrahim mahrir

    var values = [
      undefined,
      null,
      false,
      true,
      0,
      -1,
      1,
      NaN,
      Infinity,
      '',
      '123',
      'abc123',
      '123abc',
      [],
      [0],
      [1],
      {},
      {a: 1},
      function(){}   
    ];
    var foo = {bar: null};
    
    values.forEach(function(value) {
      foo.bar = value;
      
      console.log("foo.bar + '' + foo.bar:", foo.bar + '' + foo.bar);
      console.log("'' + foo.bar + '':", '' + foo.bar + '');
    });
        2
  •  15
  •   ibrahim mahrir    6 年前

    +

    1 + 1 + ''                          // results in '2'
    

    '' + 1 + 1                          // results in '11'
    
        3
  •  5
  •   Jonas Wilms    6 年前

    valueOf() toString()

     AdditiveExpression + MultiplicativeExpression
    
        4
  •  3
  •   trincot    6 年前

    foo.bar valueOf toString

    +

    const foo = { 
        bar: {
            valueOf() {
                console.log('valueOf');
                return this; // not a primitive value, so now toString will be called.
            },
            toString() {
                console.log('toString');
                return "1";
            }
        }
    }
    
    console.log(foo.bar + '');
    console.log("====");
    console.log('' + foo.bar);
        5
  •  2
  •   Zohaib Ijaz    6 年前