1. ForEach

Javascript Array forEach() 中无法 returnbreak

var arr = [1,2,3,4,5];
var num = 3;
arr.forEach(function(v){
   if(v == num) {
       break;
   }
   console.log(v);
});

会报如下错误:

var arr = [1,2,3,4,5];
var num = 3;
arr.forEach(function(v){
   if(v == num) {
       return;
   }
   console.log(v);
});

使用return也不能跳出整个循环:

forEach 实现的源代码

Array.prototype.forEach = function(fun /*, thisp*/)
{
  var len = this.length;
  if (typeof fun != "function")
    throw new TypeError();

  var thisp = arguments[1];
  for (var i = 0; i < len; i++)
  {
    if (i in this)
      fun.call(thisp, this[i], i, this);
  }
};

针对这个问题可以使用数组的另外两个方法some()与every():

some():当内部return true时跳出整个循环

var arr = [1,2,3,4,5];
var num = 3;
arr.some(function(v){
   if(v == num) {
       return true;
   }
   console.log(v);
});

// 1
// 2
// true

every():当内部return false时跳出整个循环

var arr = [1,2,3,4,5];
var num = 3;
arr.every(function(v){
   if(v == num) {
       return false;
   }else{
       console.log(v);
       return true;
   }
});

// 1
// 2
// false

2. forforEach 性能对比

let arrs = new Array(100_000);

console.time('for');
for (let i = 0; i < arrs.length; i++) {};
console.timeEnd('for');

console.time('forEach');
arrs.forEach((arr) => {});
console.timeEnd('forEach');

// for: 2.275146484375ms
// forEach: 0.23486328125ms

在10万这个级别下, forEach 的性能是for的 10 倍

let arrs = new Array(1_000_000);

console.time('for');
for (let i = 0; i < arrs.length; i++) {};
console.timeEnd('for');

console.time('forEach');
arrs.forEach((arr) => {});
console.timeEnd('forEach');

// for: 9.620849609375ms
// forEach: 2.5791015625ms

在100万这个级别下, forEach 的性能是for的 4 倍

let arrs = new Array(100_000_000);

console.time('for');
for (let i = 0; i < arrs.length; i++) {};
console.timeEnd('for');

console.time('forEach');
arrs.forEach((arr) => {});
console.timeEnd('forEach');

// for: 769.68017578125ms
// forEach: 1661.35009765625ms

在1亿这个级别下, for 的性能是forEach的 2 倍多

数据量越大,forEach的性能低于for的性能

3. for 嵌套循环

console.time('first time');
for (let i = 0; i < 100; i++) {
  for (let j = 0; j < 1000; j++) {
    for (let k = 0; k < 10000; k++) {
    }
  }
}
console.timeEnd('first time');

console.time('two time');
for (let i = 0; i < 10000; i++) {
  for (let j = 0; j < 1000; j++) {
    for (let k = 0; k < 100; k++) {

    }
  }
}
console.timeEnd('two time');

// first time: 289.223876953125ms
// two time: 432.072021484375ms

为什么呢?

1、i会循环100次,判断i<100 100次 j会循环100 * 1000次,判断j<100 100 * 1000次 k会循环100 * 1000 * 10000次,判断k<100 100 * 1000 * 10000次

2、i会循环10000次,判断i<100 10000次 j会循环10000 * 1000次,判断j<100 10000 * 1000次 k会循环100 * 1000 * 10000次, 判断k<100 100 * 1000 * 10000次

虽然判断k<100的次数都是一样的 但是前面两种判断(i 和 j)就不一样了,由此可以看见时间长短。