Fe-interview: [js] 第94天 用js写出死循环的方法有哪些?

Created on 18 Jul 2019  ·  8Comments  ·  Source: haizlin/fe-interview

第94天 用js写出死循环的方法有哪些?

js

Most helpful comment

  1. while
while (true) {

}
  1. for
for (;;) {

}

All 8 comments

while(true){
}

for(let i = 0;i<0;i++){
}

循环/递归不设置结束条件。
function fn(n){
fn(n+1)
}

非常规解法

const infiniteIterable = {
    [Symbol.iterator]() {
        const thisRef = this
        return {
            value: true, // or any other value
            next() {
                return thisRef[Symbol.iterator]()
            }
        }
    }
}
for (let _ of infiniteIterable) {
    // ...
}

while(1){
console.log('%%%%');
}

  1. while
while (true) {

}
  1. for
for (;;) {

}

1.递归不限制条件
2.while(true){ }

循环如果能结束就不是死循环,即设置一个永远达不到的结束条件就能造成死循环。

while (true) {}

for (let i = 0; i > 0; i++) {}

// 这个等价于 while
for (;;) {}

let i = 0;
do {
  i++;
} while (i > 0);

// 不设置结束条件
function fn(a) {
  console.log(a);
  fn(a);
}

递归不优化做无限循环就容易爆栈,从而报错。

Was this page helpful?
0 / 5 - 0 ratings