简体   繁体   English

当var x时,x = [x] && x.push(x)之间的javascript数组混淆;

[英]javascript array confusion between x = [x] && x.push(x) when var x;

Why does case 1 give us :error: TypeError: x is undefined on line... 为什么案例1给我们:错误:TypeError:x未在线定义...

 //case 1 var x; x.push(x); console.log(x); 

Why does case 2 shows us Array[undefined] in console 为什么案例2在控制台中显示了Array [undefined]

 //case 2 var x; var x = [x]; console.log(x); 

What is the difference between this 2 cases ? 这2个案例有什么区别?

In case one, the line x.push(x); 在第一种情况下,行x.push(x); will throw an error if x is not defined - you can't access properties of an undefined object, of course. 如果未定义x则会抛出错误 - 当然,您无法访问undefined对象的属性。

In case two, x is not defined at the point the line x = [x]; 在情况二中, x未在线x = [x];的点处定义x = [x]; is run, but you aren't trying to access any properties of x or anything like that - it's just an undefined value, which is OK. 运行,但你没有尝试访问x或任何类似的任何属性 - 它只是一个undefined值,这是好的。 So, the expression [x] results in an array with one item, x (which is undefined ), thus [undefined] . 因此,表达式[x]导致一个数组包含一个项目xundefined ),因此[undefined]

To be able to push anything values to x , you must first say that it is an array like this 为了能够将任何值推送到x ,您必须首先说它是这样的数组

var x = [];

About the variable is showing as undefined because any variable in javascript when no values is assigned to it is by default undefined. 关于变量显示为未定义,因为当没有为其分配值时,javascript中的任何变量默认为undefined。

Case 1 情况1

You are trying to invoke .push() on undefined 您正尝试在undefined上调用.push()

var x; // x is declared but value is undefined
x.push(x); // .push() can be invoked only on array types - that's why you get the error
console.log(x); // error happens before this line

Case 2 案例2

unndefined is a value in JavaScript. unndefined是JavaScript中的值。 You are creating an array with one entry - undefined . 您正在创建一个包含一个条目的数组 - undefined

var x; // x is undefined
var x = [x]; // x = [undefined] - an array with one entry - undefined
console.log(x); // prints the array

There are somethings need to be explained: 有些事情需要解释:

  1. When you declare a variable, undefined is the default value is been set. 声明变量时, undefined是已设置的默认值。 Until you set any other like var x = ''; 直到你设置任何其他像var x = ''; .
  2. [].push() is only available on arrays. [].push()仅适用于数组。

So, in your both cases: 所以,在你的两种情况下:

Case: 1 情况1

var x; // default value set to = undefined
x.push(x); // here push is undefined because undefined don't have push method.
console.log(x); // it doesn't executes because of breaking line of code above.

Case: 2 案例:2

//case 2
var x; // default value set to = undefined
var x = [x]; // now x is converted to an array and reassigned to x.
console.log(x); // logs array of one undefined value.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM