特殊书写方式

  1. var i = 1;
  2. for(; i;){
  3. console.log(i);
  4. i++;
  5. if(i == 11){
  6. i = 0;
  7. }
  8. }

循环时只去判断 i 等于 true(1) 时才循环为 0 (falsy 值) 是不循环的

示例1

var i = 100;
for(; i--;){
  console.log(i);
}

示例2

n 的阶乘

var n = 5;
var num = 1;
for(var i = 1; i <= n; i++){
  num *= i;
}
console.log(num);

示例3

789 颠倒

var num = 789;
var a = num % 10;
var b = (num - a) % 100 / 10;
var c = (num - a - b * 10) / 100;

示例4

打印三个数中最大的数

var a = 1;
var b = 2;
var c = 3;
if(a > b){
  if(a > c){
    console.log(a);
  }else{
    console.log(c);
  }
}else{
  if(b > c){
    console.log(b);
  }else{
    console.log(c);
  }
}

示例5

打印100以内的质数(仅仅能被1和自己整处的数)

var c = 0;
for(var i = 2; i <= 100; i++){
  for(var j = 1; j <= i; j++){
    if(j % i == 0){
      c++;
    }
  }
  if(c == 2){
    console.log(i);
    c = 0;
  }
}

实例6

黄金分割数列
1 1 2 3 5 8 13

// 黄金分割数列
var a1 = parseInt(window.prompt("请输入n位"));
var a = 1,
    b = 1,
    c = 0;

if(a1 <= 2){
  document.write(1);
}else{
  for(var i = 2; i < a1; i++){
    c = a+b;
    a = b;
    b = c;
  }
  document.write(c);
}

实例7

为 Type 对象增加,isNumber isString isBoolean typeof 的 3 方法

在判断语句中利用 falsy 值来控制循环

var Type = {};

for (var i = 0, type; (type = ["String", "Number", "Boolean"][i++]); ) {
  (function (type) {
    Type["is" + type] = function (obj) {
      return Object.prototype.toString.call(obj) === "[object " + type + "]";
    };
  })(type);
}

console.log(Type.isString("123"));
console.log(Type.isNumber(123));
console.log(Type.isBoolean(false));