Javascript console.log(object) vs. concatenating string

后端 未结 5 644
孤城傲影
孤城傲影 2020-12-03 02:26

I\'m running this in node.js:

> x = { \'foo\' : \'bar\' }
{ foo: \'bar\' }
> console.log(x)
{ foo: \'bar\' }
undefined
> console.log(\"hmm: \" + x)
         


        
5条回答
  •  死守一世寂寞
    2020-12-03 03:08

    The console.log function

    'console.log' is an overloaded function that accepts a list of parameters that are either passed by copy (string|number|boolean) or by reference (everything else).

    In the case of values passed by copy, the value is printed by casting it as a string.
    In the case of values passed by reference, the value is pretty printed as the browser sees fit.

    The + operator

    The plus sign operator (+) is overloaded. When both sides of the operator are numbers, the sum of the two operators is returned.

    If either side of the operator is a string, then both sides will be cast as string and the concatenation of those two strings will be returned.

    console.log("hmm: " + x);
    

    is the same as writing

    console.log(String("hmm: ") + String(x));
    

    Solution

    Prevent the implicit string casting by swapping the plus sign (+) with a comma (,)

    console.log("hmm: ", x);
    

    More Info

    For a more in depth description of the 'console.log' function, see:
    https://developer.mozilla.org/en-US/docs/DOM/console.log

    For a more in depth description on the plus sign operator (+), see:
    http://www.w3schools.com/js/js_operators.asp

提交回复
热议问题