一,变量类型(string/boolean/number/null/undefined)
val_i=23 val_i=1e3 (1000) val_i=010 (八进制) val_i=0xff (十六进制) val_s="Hello World" val_b=true typeof val_i var b; b === undefined; // true b === "undefined"; // false typeof b === "undefined"; // true typeof b === undefined; // false //字符串转数字 parseInt("123")
二,数组
//Array var arr = [1, "yes", false, null, undefined, [1,2,3]] arr.length //6 typeof arr //object arr[0] ~ arr[arr.length - 1] val_arr = arr.pop() // val_arr = [1,2,3] arr.push([1,2,3]) arr.push("new item") //Associate Array arr_a = {"name":"ciaos",'age':26} typeof arr_a //object arr_a["name"]//"ciaos" arr_a.name //"ciaos" //遍历方式 for (var key in arr_a) {out+=key+":"+arr_a[key]+"¥n"} if("name" in arr_a) if(arr_a["name"]) if(arr_a.name)
三,流程控制语句
//While | For | Do While i = 1; sum = 0; while (i <= 100) { sum += i++; } for (i = 1, sum = 0; i <= 100; i++) { sum += i; } do { sum += i++; } while (i <= 100); //Switch var a = ""; var result = ""; switch (a) { case false: result = "a is false"; break; case a + "hello": // Expressions are allowed here result = "what?"; break; case "": // Strict comparison result = "a is an empty string"; break; default: result = "@#$"; } //Try Catch Finally var msg = ""; try { throw new Error("ouch"); } catch (e) { msg += e.message; } finally { msg += " - finally"; } msg; // "ouch - finally"
四,函数
function funName(a,b){} function sum(/* nothing here */) { for (var i = 0, result = 0; i < arguments.length; i++) { result += arguments[i]; } return result; } sum(); // 0 sum(111); // 111 sum(1, 2); // 3 sum(1, 2, 3); // 6 sum(1, 10, 2, 9, 3, 8); // 33 // var sum_t = sum sum_t(1) var immediate_one = function () { return 1; }(); immediate_one // 1 var immediate_one = function () { return 1; }; immediate_one() // 1 //闭包 function declare() {} var express = function () {}; (function () { // Local scope function declare() {} // Declared and given a value var express = undefined; // Declared here console.log(typeof declare); // "function" console.log(typeof express); // "undefined" express = function () {}; // Implemented here console.log(typeof declare); // "function" console.log(typeof express); // "function" }());
五,面向对象
// function Dog() { this.name = "Fido"; this.sayName = function () { return "Woof! " + this.name; }; // 默认返回 return this; } var fido = new Dog(); fido.sayName(); // "Woof! Fido" function Dog() { var notthis = { noname: "Anonymous" }; this.name = "Fido"; return notthis; } var fido = new Dog(); fido.name; // undefined fido.noname; // "Anonymous" function Dog() { this.name = "Fido"; return 1; } var fido = new Dog(); typeof fido; // "object" fido.name; // "Fido" var one = Dog(); one; // 1 //使用sayName添加成员函数 Dog.prototype.sayName = function () { return this.name; };
六,其它
JSON.stringify({hello: "world"}); // '{"hello":"world"}' JSON.parse('{"hello":"world"}').hello; // "world"