選擇(分支)語句
if語句
// if 單分支語句語法:
if (condition) {
// 滿足條件執(zhí)行這里
} else {
// 不滿足條件執(zhí)行這里
}
// 單分支語句可以用三元運(yùn)算表示:
// 語法: 條件 ? 條件成立代碼 : 條件不成立代碼
// 例如
a > b ? a : b // 該語句表示:如果a大于b則返回a,否則返回b
// if多分支語句語法:
if (condition1) {
// 滿足條件1姓蜂,執(zhí)行這里的代碼
} else if (condition2) {
// 滿足條件2橱健,執(zhí)行這里的代碼
} else if (condition3) {
// 滿足條件3郎任,執(zhí)行這里的代碼
} else {
// 如果都不滿足鼓黔,執(zhí)行這里的代碼
}
switch語句
// switch語法
switch (condition) {
case value1:
// 條件恒等于value1,執(zhí)行這里的代碼
break;
case value2:
// 條件恒等于value2携御,執(zhí)行這里的代碼
break;
default:
// 如果都不滿足纳本,執(zhí)行這里的代碼
}
循環(huán)語句
while循環(huán)語句
// while 循環(huán)語句
while (condition) {
// 條件成立,不斷執(zhí)行這里的代碼土思,直到條件不成立务热,這里一般包含條件更新語句
}
// while循環(huán)語句可能永遠(yuǎn)不會被執(zhí)行
// do...while循環(huán)語句
do {
// 不管滿不滿足條件,先執(zhí)行這里的語句己儒,再判斷是否滿足條件崎岂,是,繼續(xù)執(zhí)行闪湾,否冲甘,跳出循環(huán),這里一般也包含條件更新
} while (condition)
// do...while循環(huán)語句常用于至少要被執(zhí)行一次的情形
for循環(huán)語句
for (變量初始化; 條件; 變量更新) {
// 執(zhí)行這里的代碼
}
循環(huán)跳轉(zhuǎn)
break // 跳出當(dāng)前循環(huán)
continue // 跳出本次循環(huán)途样,繼續(xù)下一次循環(huán)江醇,不推薦使用,我們可以通過修改循環(huán)體何暇,達(dá)到相同的效果
label // 給循環(huán)代碼添加標(biāo)識
循環(huán)語句的使用場景
固定次數(shù)的循環(huán)用for語句陶夜,不固定次數(shù)的循環(huán)使用while語句或者do...while語句
ES5, ES6,JQuery的 循環(huán)語句赖晶,方法
Array.forEach(function (value, index, array) {})
forEach()方法是ES5新增的數(shù)組方法律适,只能遍歷數(shù)組,而且不能被終止(break無效)
[1,2,3].forEach(function(value, index, array) {
console.log(value, index, array)
})
// 1 0 [1,2,3]
// 2 1 [1,2,3]
// 3 2 [1,2,3]
$.each([], function (index, value, array) {})
$.each()是jquery的遍歷方法遏插,能夠遍歷數(shù)組捂贿,對象,參數(shù)和forEach()相反
$.each([1,2,3], function(index, value, array) {
console.log(index, value, array)
})
// 0 1 [1,2,3]
// 1 2 [1,2,3]
// 2 3 [1,2,3]
for in 遍歷 (ES5)
能夠遍歷數(shù)組胳嘲,對象厂僧,但是不推薦遍歷數(shù)組,for...in循環(huán)出的是key, 而且原型鏈上的屬性也會被遍歷到了牛,因此一般常用來遍歷非數(shù)組的對象并且使用hasOwnProperty()方法去過濾掉原型鏈上的屬性
var myArry =[1,2,3,4];
myArry.desc ='four';
for (var value in myArry) { //循環(huán)key
console.log(value)
}
// 0
// 1
// 2
// 3
// 'desc'
// 結(jié)論:所以一般使用for in 循環(huán)對象
for of 遍歷 (ES6)
for...of循環(huán)出的是value, 適合遍歷數(shù)組颜屠,
這個方法是最簡潔的,并且修復(fù)了for-in
循環(huán)的所有缺點(diǎn),與forEach()
不同的是,它可以正確的響應(yīng)break,contine,return
語句
不僅如此,for-of
還可以支持大部分的類數(shù)組對象 ==注意:for-of
循環(huán)不支持普通對象,但是如果你想迭代一個對象的屬性,可以使用for-in
循環(huán)(這也是它的本職工作)或者內(nèi)建的Object.keys()
方法==
var a = ["a", "b", "c"];
for (var value of a) { // 循環(huán)的是value
console.log("for of:" + value);
}
// for of:a
// for of:b
// for of:c