JavaScript arrayToList

前端 未结 2 1006
失恋的感觉
失恋的感觉 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: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]));

提交回复
热议问题