为什么Javascript的每种方法都被制服了?

Tha*_*Fog 0 javascript arrays performance benchmarking loops

我已经制定了基准来检查几种迭代数组的方法的性能.

https://jsperf.com/extended-array-loops-performance

有人可以解释为什么every方法如此强大?它比任何其他方法快90%以上,甚至比那些类似的方法更加奇怪

sam*_*ime 6

因为你只运行一次.

every() 将循环遍历元素,直到找到falsey值,此时它将返回.

由于你的基准测试没有返回任何东西,也就是说undefined,falsey它只运行一次.所有其他循环都会遍历所有元素.

将您的测试更改为:

arr.every(val => {
  sth = val;
  return true;
});
Run Code Online (Sandbox Code Playgroud)

它应该与其他人一致.