【问题标题】:JavaScript arrayToListJavaScript 数组列表
【发布时间】:2018-01-31 20:16:53
【问题描述】:

谁能帮我弄清楚我在代码中做错了什么? 因为我想创建一个函数,它可以帮助我将所有数组数据转换为列表并打印出来。

原始说明 ****编写一个函数 arrayToList,当给定 [1, 2, 3] 作为参数时,它建立一个与前一个类似的数据结构,并编写一个 listToArray 函数,它从一个列表中生成一个数组。还要编写辅助函数 prepend,它接受一个元素和一个列表并创建一个新列表,将元素添加到输入列表的前面,以及 nth,它接受一个列表和一个数字并返回给定位置的元素列表,如果没有这样的元素,则为 undefined。 如果你还没有,也写一个递归版本的 nth.****

function arrayToList(arrayx){
for(var i=10;i<arrayx.length;i+=10)
var list = {
 value: i,
 rest: {
   value: i+=10,
   rest: null}}
return list;
}

我想要的结果是

console.log(arrayToList([10, 20]));

// → {value: 10, rest: {value: 20, rest: null}}

【问题讨论】:

  • 这个的用例是什么?这似乎太复杂了..
  • 在这种情况下,您需要将对象数组作为列表返回
  • 正如@Erazihel 所说,我发现这真的很复杂。你能告诉我们列表的最终用例是什么吗?
  • Ohhhh....好吧,这是练习的原始内容:
  • @Okazari 我在问题中添加了一些原始说明,这有帮助吗?

标签: javascript arrays list


【解决方案1】:

你也可以试试这个:

    
    
    function arrayToList(arrayx){ 
    for(var i = arrayx[0];i < Math.max.apply(Math,arrayx); i+=arrayx[0])
    {
     var list = {
     value: i,
     rest: {
     value: i+=10,
     rest: null
       }
      }
    return list;
    }
    }
    
    console.log(arrayToList([10 , 20]));

【讨论】:

  • 请问“Math.max.apply”是什么?
  • 从数组中查找最大值。不能使用 array.length ,因为根据您的例如,您的数组长度将为 2 或 3,但第一个数组元素为 10,因此循环条件永远不会满足
  • 如果您能投票并接受它作为答案,如果这对您有帮助,我们将不胜感激
  • 当然,我会这样做的!
【解决方案2】:

    // This is a function to make a list from an array
    // This is a recursive function
    function arrayToList(array) {
        // I use an object constructor notation here
        var list = new Object();
        // This is to end the recursion, if array.length == 1, the function won't call itself and instead
        // Just give rest = null
        if (array.length == 1) {
            list.value = array[array.length - 1];
            list.rest = null;
            return list;
        } else {
            // This is to continue the recursion.  If the array.length is not == 1, make the rest key to call arrayToList function
            list.value = array[0];
            // To avoid repetition, splice the array to make it smaller
            array.splice(0,1);
            list.rest = arrayToList(array);
            return list;
        }
    }
    
    
console.log(arrayToList([10, 20]));

【讨论】:

    猜你喜欢
    • 2015-01-13
    • 2023-01-14
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 2014-06-05
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多