控制结构
任何一门编程语言都有控制结构,它们的细节也许不同,但是遵循相同的基本规律。JavaScript也不例外。
A control structure is a block of programming that analyzes variables and chooses a direction in which to go based on given parameters. The term flow control details the direction the program takes (which way program control “flows”).
if-else
/* Example 01 - if */
var num = 1;
if (num === 1) {
console.log("num is equal to 1");
}
/* Example 02 - if-else */
var num = 0;
if (num === 1) {
console.log("num is equal to 1");
} else {
console.log("num is not equal to 1, the value of num is " + num);
}
/* Example 03 - if-else-if-else... */
var month = 5;
if (month === 1) {
console.log("January");
} else if (month === 2){
console.log("February");
} else if (month === 3){
console.log("March");
} else {
console.log("Month is not January, February or March");
}
/* Example 04 - switch */
var month = 5;
switch(month) {
case 1:
console.log("January");
break;
case 2:
console.log("February");
break;
case 3:
console.log("March");
break;
default:
console.log("Month is not January, February or March");
}
/* Example 05 - ternary operator - if..else */
if (num === 1){
num--;
} else {
num++;
}
//is the same as
(num === 1) ? num-- : num++;
运行结果:
以上是JavaScript的条件语句。
for/do-while/while
console.log('**** for example ****');
/* for - example */
for (var i=0; i<10; i++) {
console.log(i);
}
console.log('**** while example ****');
/* while - example */
var i = 0;
while(i<10)
{
console.log(i);
i++;
}
console.log('**** do-while example ****');
/* do-while - example */
var i = 0;
do {
console.log(i);
i++;
} while (i<10)
运行结果:
以上展示的是JavaScript的loop。
function
function sayHello() {
console.log('Hello!');
}
sayHello();
/* function with parameter */
function output(text) {
console.log(text);
}
output('Hello!');
output('Hello!', 'Other text');//The second parameter is neglected.
output();//This is undefined because of the parameter number is 0 which can not match with the original function itself.
/* function using the return statement */
function sum(num1, num2) {
return num1 + num2;
}
var result = sum(1,2);
output(result);
以上展示了JavaScript的函数的基本语法。
object
/* Object example 1 */
var obj = new Object();
/* Object example 2 */
var obj = {};
obj = {
name: {
first: 'Gandalf',
last: 'the Grey'
},
address: 'Middle Earth'
};
/* Object example 3 */
function Book(title, pages, isbn){
this.title = title;
this.pages = pages;
this.isbn = isbn;
this.printIsbn = function(){
console.log(this.isbn);
}
}
var book = new Book('title', 'pag', 'isbn');
console.log(book.title); //outputs the book title
book.title = 'new title'; //update the value of the book title
console.log(book.title); //outputs the updated value
Book.prototype.printTitle = function(){
console.log(this.title);
};
book.printTitle();
book.printIsbn();
JavaScript里面的对象是普通的名值对的集合。类可以包含函数,也可以声明和使用函数。或者在类里面声明函数。基于原型的方法可以节约内存、降低实例化的开销。声明公共方法时最好使用基于原型的方法。生成私有方法时,采用在类定义时内部声明的方式,这样其他实例不会访问这个方法。一般情况下,尽量使用基于原型的方法定义更好。