標籤:javascript為什麼會有 unde javascript undefined
ECMAScript variables are loosely typed, meaning that a variable can hold any type of data. Every
variable is simply a named placeholder for a value. To define a variable, use the var operator (note
that var is a keyword) followed by the variable name (an identifier, as described earlier), like this:
var message;
This code defines a variable named message that can be used to hold any value. (Without
initialization, it holds the special value undefined, which is discussed in the next section.)
ECMAScript implements variable initialization, so it’s possible to define the variable and set its
value at the same time, as in this example:
var message = “hi”;
Here, message is defined to hold a string value of “hi”. Doing this initialization doesn’t mark
the variable as being a string type; it is simply the assignment of a value to the variable. It is still
possible to not only change the value stored in the variable but also change the type of value, such
as this:
var message = “hi”;message = 100;//legal, but not recommended
In this example, the variable message is first defined as having the string value “hi” and then
overwritten with the numeric value 100. Though it’s not recommended to switch the data type that
a variable contains, it is completely valid in ECMAScript.
From:
Professional JavaScript for Web Developers (2012)
[個人意見,純屬個人理解]JavaScript是弱類型語言,一個變數可以是任何類型,而且隨著賦值或初始化於值的不同而改變,那如果一個變數只聲明不初始化也不賦值,這個變數編譯器預設初始化什麼呢。
C,C++,java語言是強型別的,都會根據其類型提供預設初始化,但JavaScript編譯器沒能力判斷,所以必須提供一個與上述語言不同的預設值,估計就這樣,選擇undefined了。
JavaScript為什麼會有 undefined值。