javascript - 如何在 javascript 中使用递归来创建键值对象

标签 javascript recursion

我了解如何使用循环来处理任务,递归对我来说有点神秘,但据我了解,在某些情况下,如果循环遍历大量数据,它可以节省大量时间。

我创建了以下函数来循环遍历大型(大概)数据集。

var quotes = require('./quotes.js');
//Pulls in the exported function from quotes.js
var exportedQuotes = quotes.allQuotes();
var allAuthors = exportedQuotes.author;
//Create an empty key value object, we use these to coerce unique values to an array
var uniqs = {};
//I create this object to hold all the authors and their quotes
var fullQuote = {};
//Create an object with only unique authors
for(var i = 0; i < allAuthors.length ; i++){
        fullQuote[allAuthors[i]] = null;
}
//Coerce unique authors from javascript object into an array
var uniqAuthors = Object.keys(uniqs);

var quoteCount = exportedQuotes.author.length;



var iterativeSolution = function(){
        for(var i = 0; i < Object.keys(fullQuote).length; i++){
            for(var j = 0; j < exportedQuotes.author.length; j++){
                //If the author in the unique list is equal to the author in the duplicate list
                if(Object.keys(fullQuote)[i] == exportedQuotes.author[j]){
                    //if an author has not had a quote attributed to its name
                    if(fullQuote[exportedQuotes.author[j]] == null){
                        //assign the author an array with the current quote at the 0 index
                        fullQuote[exportedQuotes.author[j]] = [exportedQuotes.quote[j]]
                    } else {
                        //if an author already has a quote assigned to its name then just add the current quote to the authors quote list
                        fullQuote[exportedQuotes.author[j]].push(exportedQuotes.quote[j])
                    }
                }
            }
        }
    }

我目前没有分析这个的技能,但是,我想知道是否有递归的情况来节省通过所有循环所需的时间。如果存在递归的情况,javascript 中的嵌套循环会是什么样子,特别是在递归创建键值对象时?

最佳答案

关于什么是递归,可能有一点误解:递归不节省时间。这只是进行相同遍历的不同方式。它通常更容易阅读,并且根据问题,会更好地映射到某些算法。然而,当我们需要开始优化代码以提高速度时,我们要做的第一件事就是删除递归,将它们变回循环,然后甚至“展开”循环,使代码更加丑陋,但是快,在过程中。递归与普通循环几乎总是一个品味问题。一个看起来更好,但这并不是我们判断代码的唯一质量。

而且:虽然听起来我在提倡不要使用它,但这并不意味着您不应该尝试一下:获取该代码,将其放入一个新文件中,重写该文件以便它使用递归.这样做可以让您比较您的代码。哪个更快?哪个更容易阅读?现在您对(您的)代码的行为有所了解,并且您将学到一些有值(value)的东西。

也不要低估自己:如果您编写了这段代码,您就知道它是如何工作的,因此您知道如何分析它以重写它。

关于javascript - 如何在 javascript 中使用递归来创建键值对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30970324/

相关文章:

javascript - Internet Explorer跨域请求无法正常工作并且MS没有给出onerror推理

javascript - 具有缓动和触摸功能的滚动条插件

c++ - Python 实现不适用于 C++ 中的相同逻辑

recursion - 如何从递归 LISP 函数返回?

algorithm - 如果递归函数的输入大小减少 2,它是阶乘时间算法吗?

ASP.Net Webforms 的 Javascript 框架

javascript - 跨站脚本: Is restricting the use of < and > tags an effective way to reduce Cross Site Scripting?

javascript - 未捕获的 TypeError : textLocation[p]. find 不是一个函数

c# - 使用递归属性 ASP.NET/C#

javascript - 绘制分形时迭代更改 Canvas 中的 fillStyle 颜色