【问题标题】:Console.log vs printing out variableConsole.log 与打印出变量
【发布时间】:2018-02-21 17:19:41
【问题描述】:

当我使用console.log 在控制台窗口中为一个不在引号中的字符串打印一个值时,怎么会这样,但是当我只是在控制台中输出变量时,它会打印引号。这有什么特别的原因吗?

var test = “hello”; 
test; 
Output : “hello”

Console.log(test); 
Output: hello

【问题讨论】:

  • 是的,console.log 仅用于输出文本。但是如果你输入一个变量,你会得到这个对象的检查器。所以是的,是有区别的。

标签: javascript console console.log


【解决方案1】:

嗯,这样看。

var test = "hello"; 
test;  // This is object in self and what is it,
       // it is a string in literal 

// Output comes only from debugger , when you input direct.
// test; this line have no output to the console
// Output : "hello" NO

//console.log(test); // console.log already print string (in native/string is output) but also print objects.
// Output: hello YES

console.log( test + " this is the test")

// See output it is a very clear 
// hello this is the test

【讨论】:

    【解决方案2】:

    默认行为是在控制台中将字符串与引号一起表示。

    a = 'hi';
    a
    // returns "hi"
    

    console api 是不同的,是一个例外。

    console.log(object [, object, ...]) 在控制台中显示一条消息。将一个或多个对象传递给此方法。每个对象都被评估并连接成一个以空格分隔的字符串。

    所以它返回一个以空格分隔的连接字符串。这意味着它将始终是一个字符串。由于它总是一个字符串,我们可以取消引号。我想控制台开发人员让这种方式表明 console.log() 将始终返回相同的类型(字符串)。添加引号可能意味着它可能会返回其他内容,因此它似乎是控制台的用户体验。

    【讨论】:

      【解决方案3】:

      Javascript 是动态类型的,这意味着变量可以随时存储任何类型的值。如果您调用存储字符串的变量(在您的情况下为测试),它会打印出值“Hello”,指示其为字符串并返回字符串数据类型,这非常简单。但数字也可以是字符串,如 var a = "5"。另一方面,console.log() 只是打印变量内部的值,默认返回 undefined。

      var a = "hello";
      // To check the return type of variable a which is string
      console.log(typeof(a));
      
      // To check the return type of console.log() which is undefined
      
      console.log(typeof(console.log(a)));

      【讨论】:

      • 建议包括一些解释和代码。
      猜你喜欢
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多