JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings, arrays, objects and more:
var length = 16; // Number
var lastName = "Johnson"; // String
var cars = ["Saab", "Volvo", "BMW"]; // Array
var x = {firstName:"John", lastName:"Doe"}; // Object
The Concept of Data Types
In programming, data types is an important concept.
To be able to operate on variables, it is important to know something about the type.
Without data types, a computer cannot safely solve this:
var x = 16 + 4 + "Volvo"; //Result:20Volvo
var x = "Volvo" + 16 + 4; //Result:Volvo164
JavaScript Has Dynamic Types
JavaScript has dynamic types. This means that the same variable can be used as different types:
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
早期的程式語言對資料型態都非常嚴緊,JS變數的資料型態由存放的值來決定。簡言之就是考慮存入值就好。這一點對使用上是有強大的便利性的,缺點是無法精確的掌控占用資源多寡。因此如果適當的處理資料型態以有效率使用資源,是進階/優化程序的更進一步技術。
JavaScript Strings
JavaScript Numbers
JavaScript Booleans
JavaScript Arrays
JavaScript Objects
Strings,Numbers,Booleans,Arrays,Objects再另作詳解!
The typeof Operator
You can use the JavaScript typeof operator to find the type of a JavaScript variable:
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
In JavaScript, an array is a special type of object. Therefore typeof [1,2,3,4] returns object.
Undefined (未定義)
In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.
var person; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will also be undefined.
person = undefined; // Value is undefined, type is undefined
由這個例子,更能說我上段由值來決定型態,沒有放入值就等同沒有型態。而第二例再宣告是未定義,是不是多此一舉。
Empty Values (空字串)
An empty value has nothing to do with undefined.
An empty string variable has both a value and a type.
var car = ""; // The value is "", the typeof is string
Null (零)
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.
You can consider it a bug in JavaScript that typeof null is an object. It should be null.
在上面解釋Null 在typeof 是一個Object是一個bug。但我突然覺得因為Null的值,即不表明那一類的型態,那麼就是最大型態概說,所以才歸到物件。又就物件導向的觀點,有定義:物件應該包括其它所有類型。
You can empty an object by setting it to null:
var person = null; // Value is null, but type is still an object
You can also empty an object by setting it to undefined:
var person = undefined; // Value is undefined, type is undefined
Difference Between Undefined and Null
typeof undefined // undefined
typeof null // object
null === undefined // false 完全相等是要值/型一致,因此為否。
null == undefined // true 相等則為真則應該只判斷值而沒對型態。
詳細內容可以參考:
- w3school.com (http://www.w3schools.com/)
-
程式語言教學誌(http://pydoing.blogspot.tw/)
沒有留言:
張貼留言