JavaScript為什麼會有 undefined值。

來源:互聯網
上載者:User

標籤: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值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.