码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript为什么会有 undefined值。

时间:2015-06-28 12:45:27      阅读:134      评论:0      收藏:0      [点我收藏+]

标签: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值。

标签:javascript为什么会有 unde   javascript undefined   

原文地址:http://blog.csdn.net/doctor_who2004/article/details/46670237

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!