What is console.log?

前端 未结 22 2711
面向向阳花
面向向阳花 2020-11-22 00:41

What is the use of console.log?

Please explain how to use it in JavaScript, with a code example.

22条回答
  •  故里飘歌
    2020-11-22 01:00

    A point of confusion sometimes is that to log a text message along with the contents of one of your objects using console.log, you have to pass each one of the two as a different argument. This means that you have to separate them by commas because if you were to use the + operator to concatenate the outputs, this would implicitly call the .toString() method of your object. This in most cases is not explicitly overriden and the default implementation inherited by Object doesn't provide any useful information.

    Example to try in console:

    >>> var myObj = {foo: 'bar'}
    undefined
    >>> console.log('myObj is: ', myObj);
    myObj is: Object { foo= "bar"}
    

    whereas if you tried to concatenate the informative text message along with the object's contents you'd get:

    >>> console.log('myObj is: ' + myObj);
    myObj is: [object Object]
    

    So keep in mind that console.log in fact takes as many arguments as you like.

提交回复
热议问题