为什么给定JavaScript代码的输出是字符串?

时间:2017-03-07 11:00:50

标签: javascript

var z = 1,
  y = z = typeof y;
console.log(z); // >> 'string'

为什么z的值是字符串。

5 个答案:

答案 0 :(得分:0)

它正在提升变量的声明,其值为'undefined'



var z, y;

z = 1,
y = z = typeof y;

console.log(z, typeof z);
console.log(y, typeof y);




答案 1 :(得分:0)

你得到string是正常的,因为你在z中存储了typeof y表达式的结果,它会给你一个包含类型的字符串你的对象。

请考虑以下事项:

var a = typeof undefined;
console.log(a); // returns "undefined" which is string.

答案 2 :(得分:0)

如果您只运行此代码,则z的值为"undefined"。如果您多次运行,z的值将为"string"

故障:

var z = 1, y = z = typeof y;
console.log(z); // >> 'string'

按以下顺序执行:

  1. 将1分配给zz的值为1
  2. 评估typeof y。此评估结果为"undefined",因为y的值为undefined
  3. 评估z = "undefined"z的值为"undefined"
  4. 评估y = "undefined"y的值为"undefined"
  5. 记录z的值。这会记录undefined
  6. 第二次运行,你得到:

    1. 将1分配给zz的值为1
    2. 评估typeof y。此评估结果为"string",因为y的值为"undefined"
    3. 评估z = "string"z的值为"string"
    4. 评估y = "string"y的值为"string"
    5. 记录z的值。这会记录string

答案 3 :(得分:0)

返回undefined字符串,因为您将typeof y的结果分配给z变量,此时未定义y。另请注意,typeof运算符始终返回指示类型的字符串。

答案 4 :(得分:0)

您的代码幕后发生的事情如下:

  1. 解释器看到关键字“var”,并为引用名称“z”和“y”创建一些内存,默认值为undefined。在您的情况下,您没有明确使用关键字“var”表示“y”,因为您使用的是一种简写方法,该方法可转换为:
  2. var z = undefined;
    var y = undefined;
    
    1. 在第二步中,值的分配发生。请注意,您将“y”中的值指定为“z”,这是“y”的类型,在这种情况下是未定义的:
    2. z = 1;
      console.log(z) // z is now 1
      z = typeof y
      console.log(z) // undefined
      console.log(y) // undefined
      y = z
      console.log(z) // undefined
      console.log(y) //undefined
      

      不要被未定义的结果欺骗并将其视为字符串。

      console.log(typeof undefined) // "undefined"
      console.log(typeof "undefined") // string
      

      Undefiend是一种类型,除非你在这种情况下明确地指定为“undefined”,引号使它成为一个字符串

      在您抛出“string”的情况下,您必须使用console.log(typeof z)并抛出字符串,因为您已将z指定为“undefined”而非未定义