雄辩的Javascript第4章:arrayToList / listToArray执行 [英] Eloquent Javascript Chapter 4: arrayToList/listToArray Execise

查看:44
本文介绍了雄辩的Javascript第4章:arrayToList / listToArray执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

雄辩的JavaScript提出的问题


编写一个函数arrayToList,当给定[1、2、3]作为参数时,它会构建一个类似于
的数据结构,并编写一个listToArray
函数,该函数从一个列表。还要编写辅助
函数prepend,该函数接受一个元素和一个列表,并创建一个新的
列表,该元素将元素添加到输入列表的前面,第n个
接受一个列表和一个数字,并返回列表中给定
位置的元素,如果没有此类元素,则返回undefined。

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.

任何人都可以不带任何术语解释这个答案吗?
我只能按照说明学习。

Can anyone explain this answer without any jargon? I can only learn by instructions.

这是我为arrayToList想到的:
因此,开始列表为null,为循环递减创建并在内部定义 i,然后返回列表。

Here is what I came up with for arrayToList: So start list null, create for loop decrementing and inside define "i" then return list.

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;
}

rest:list 列表对象内?

推荐答案


列表对象内的 rest:list 是什么?

它将在对象文字中创建属性 rest ,并为其分配变量 list的值-在将​​该对象分配给变量 list 之前。请注意,这是循环发生的,因此要做的就是获取旧值并用引用旧值的新值覆盖它。

It creates a property rest in the object literal, and assigns to it the value of the variable list - before assigning that object to the variable list. Notice that this happens in a loop, so what it does is to take the old value and overwrite it with a new value that references the old value.

这就是您所需要的


var list = null;来构建嵌套列表结构。 //不知道为什么我们将其设置为空

这是初始值,它将被放置在列表的末尾。如果该数组为空,则将返回该数组;如果该数组具有一个元素,它将成为返回对象的 rest 属性。如果数组有多个元素…

That's the initial value, which will be placed at the "end" of the list. If the array is empty, it will be returned, if the array has one element it will become the rest property of the object that is returned. If the array has more than one element…


为什么长度为-1?

why -1 on the length?

因为数组的索引为零,即它们的索引从 0 length-1 。当我们向后迭代时,我们需要这个奇数初始值和 i> = 0 比较。

Because arrays are zero-indexed, i.e. their indices run from 0 to length-1. When we iterate backwards, we need this odd initial value and the i >= 0 comparison.

这篇关于雄辩的Javascript第4章:arrayToList / listToArray执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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