查看类型typeof variable
简单数据返回string number boolean undefined
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof true // Returns "boolean"
typeof false // Returns "boolean"
typeof x // Returns "undefined" (if x has no value)
复杂类型(objects, arrays, null,function)返回function或object
typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4] // Returns "object" (not "array", see note below)
typeof null // Returns "object"
typeof function myFunc(){} // Returns "function"
字符串(Strings)
var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';
var carName3 ="'Volvo XC60'"
数字(Numbers)
var x1 = 34.00;
var x2 = 34;
布尔(Booleans)
var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false
数组(Arrays)
var cars = ["Saab", "Volvo", "BMW"];
字典(Dictionary)
var dict = {
FirstName: "Chris",
"one": 1,
1: "some value"
};
// 访问字典
dict["one"] = 1;
dict[1] = "one";
// 更新字典
dict["Age"] = 42;
dict.FirstName = "Chris";
//遍历
for(var key in dict) {
var value = dict[key];
// do something with "key" and "value" variables
}
对象(Objects)
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
未定义(Undefined)
在javascript中,一个变量没有值,它的类型和值都是undefined
var car; // value和type都是未定义
car = undefined;
空(NULL)
null的数据类型是object,值是null
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null; // Now value is null, but type is still an object
JSON
js对象转化为json
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
json转化为js对象
var myJSON = '{"name":"John", "age":31, "city":"New York"}';
var myObj = JSON.parse(myJSON);
alert(myObj.name)
json两种定义方式
//直接定义
var myJSON = '{"name":"John", "age":31, "city":"New York"}';
//转化而来
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
json和js对象区别:
在JSON, 键必须是strings,由两个双引号包裹
{ "name":"John" }
{ "age":9 }
在JavaScript, 键可以是strings, numbers, 或identifier names
var name = "myName"
var obj = { [name]:"John" }
json格式的数据值可以是 string number object (JSON object) array boolean null
//string
{ "name":"John" }
//number
{ "age":30 }
//object
{
"employee":{ "name":"John", "age":30, "city":"New York" }
}
//array
{
"employees":[ "John", "Anna", "Peter" ]
}
//boolean
{ "sale":true }
//null
{ "middlename":null }
但不可以是function date undefined
从服务器获取json
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();