如何避免JavaScript中的for循环内的for循环 [英] How to avoid for loop inside for loop in javascript

查看:55
本文介绍了如何避免JavaScript中的for循环内的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一段不错的代码.我想要一个新数组,该数组由myArr中的元素组成,顺序为orderArr中指定的顺序.但是,它在另一个for循环内部使用了for循环来匹配数组元素.

I've written a piece of code that works fine. I want a new array consisting of the elements from myArr in the order specified in orderArr. However, it uses for loop inside another for loop to match array elements.

var myArr = ['a', 'b', 'c', 'd', 'e'];
var orderArr = ['e', 'c'];
var reArr = [];

for (var i = 0; i < orderArr.length; i++) {
  for (var k = 0; k < myArr.length; k++) {
    if (myArr[k] == orderArr[i]) {
      reArr.push(myArr[k]);
    }
  }
}

console.log(reArr);

我经常听说在另一个for循环中使用for循环是不好的做法,甚至应避免使用forEach.

I've often heard that using for loops inside another for loop is bad practice and even forEach should be avoided.

我还能如何重新编写此代码.

How else can I re-write this code.

推荐答案

我不一定要说在循环内部使用循环是一种不好的做法-实际上,Ori Drori击败了我,指出这种做法的效率可能仅仅取决于数据集的大小.

I wouldn't necessarily say that using loops inside loops is a bad practice -- in fact Ori Drori beat me to stating that the efficiency of such a practice might simply depend on the size of the data set.

例如,有许多排序算法的实现,您经常会在其中找到循环循环.但是,随着数据大小的变化,实现的细节会影响性能.

For example, there are many implementations of sorting algorithms and you'll often find loops within loops. However the details of the implementation impact the performance as the data sizes change.

我个人的经验是,当我看到嵌套循环时,我立即问自己是否正在执行的操作需要使用其他算法进行优化.在JavaScript(浏览器)应用程序中,答案通常是否",因为数据大小很少足够大以至于不会产生重大影响.

My own personal experience is that when I see nested loops I immediately ask myself if the operation it's performing needs to be optimized with a different algorithm. More often than not in JavaScript (browser) applications the answer is "no" because data sizes are rarely big enough to make an impactful difference.

这篇关于如何避免JavaScript中的for循环内的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆