解读JavaScript中 For, While与递归的用法
for(i=start; i<end; i++) {
}
while循环: (注意, 若条件一直为真, 则会进入死循环, 浏览器就hang掉)
代码如下:
while (condition) {
//do something;
//change condition;
}
递归:
function substring(all, start, end) {
for(i=start; i<=end; i++) {
console.log(all[i]);
}
substring("eclipse", 1, 4); //clip
function substring(all, start, end) {
if(start >= end) {
return all[start];
}
else {
return all[start] + substring(all, start+1, end);
}
substring("eclipse", 1, 4); //clip
使用for循环访问对象属性:
对于数组,字符串, 我们使用index []访问特定的值; 对于对象,也是一样使用[], 但我们会使用一个特殊的变量: propertyName
代码如下:
var person = {
name: "Morgan Jones",
telephone: "(650) 777 - 7777",
email: "morgan.jones@example.com"
};
for (var propertyName in person) {
console.log(propertyName + ":"+ person[propertyName]);
}
var table = [
["Person", "Age", "City"],
["Sue", 22, "San Francisco"],
["Joe", 45, "Halifax"]
];
var i;
var rows=table.length;
for (r=0;r<rows;r++) {
var c;
var cells = table[r].length;
var rowText = "";
for (c=0;c<cells;c++) {
rowText += table[r][c];
if (c < cells-1) {
rowText += " ";
}
}
console.log(rowText);
}
结果:
Person Age City
Sue 22 San Francisco
Joe 45 Halifax
--------------------------------------------------------------------------------
break:
使用break立刻退出循环, 适用于for和while循环.