JavaScript arrayToList

前端 未结 2 1005
失恋的感觉
失恋的感觉 2021-01-28 19:28

can anyone help me figure what i did wrong in my code? Cause I wanna created a function which can help me turn all the array data into list and print the list out.

相关标签:
2条回答
  • 2021-01-28 19:39

    You may try this as well :

        
        
        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]));

    0 讨论(0)
  • 2021-01-28 19:41

        // 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]));

    0 讨论(0)
提交回复
热议问题