javascript - Eloquent Javascript 第 4 章 : arrayToList/listToArray Execise

标签 javascript arrays

Question from eloquentjavascript :

Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element.

谁能不用行话解释这个答案? 我只能按照说明学习。

这是我为 arrayToList 想出的: 所以开始列表 null,创建 for 循环递减并在内部定义“i”然后返回列表。

function arrayToList(array){ //pass list as parameter
    var list = null; // don't know why we make it null
    for (var i=array.length-1; i>=0; i--)  // why -1 on the length?
        list = {value: array[i], rest:list}; //clueless
    return list;
}

list 对象中的rest:list 是什么?

最佳答案

@eloquent 的最后一条评论需要修改:

var arr1 = [10, 20, 30];

function arrayToList(arr) {
  var list = {};

 for (var i = 0; i < arr.length; i++) {
    list.value = arr.splice(0, 1)[0];
    list.rest = (arr.length > 0) ? arrayToList(arr) : null;
 }

 return list;
}

console.clear();
console.log(  arrayToList(arr1) );

关于javascript - Eloquent Javascript 第 4 章 : arrayToList/listToArray Execise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800442/

相关文章:

javascript - 如何将 html5 Canvas 图像转换为 json 对象?

javascript - 为什么 onchange 函数不使用 Jquery 调用 DropDownList?

javascript - 如何在 grunt build 中跳过 concat

arrays - 如何在查询嵌套对象/数组时使用 "wildcard"或 "regexp"

python - 在 nd 数组的一个轴上应用一维函数

javascript - 当另一个元素消失时转换一个元素

javascript - 如何为 php 文件制作通用的 ajax 函数

php - 使用 OR 和 LIKE % 查询 PHP foreach?

php - PHP数组输出仅显示一个元素

c# - 你如何询问一个数组是否包含一个特定的类?