简体   繁体   中英

Is it possible to implement arrayToList function in JS not from stepping through the array backwards?

 function arrayToList(array) { var list = null; for (var i = array.length - 1; i >= 0; i--) //How to implement it if i = 0? list = { value: array[i], rest: list }; return list; }

arr.reverse - not offer. I'm curious how it can be done if we're stepping through the array from array[0]? Or this task in JS only can be done if we're stepping through the array backwards?

You could reduce an object and assign at the end null .

 function arrayToList(array) { var list = {}; array.reduce((o, v, i, a) => (o.value = v, o.rest = i + 1 === a.length ? null : {}), list); return list; } console.log(arrayToList([4, 5, 6, 7]));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

You could do it without a loop, using recursion instead.

 function arrayToListRecursive(arr) { return (!arr.length) ? null : { value: arr[0], rest: arrayToListRecursive(arr.slice(1)) } } function arrayToListLoop(arr) { let list = null; for (let i = 1; i <= arr.length; i++) { list = { value: arr[arr.length - i], rest: list }; } return list } console.log( arrayToListRecursive([1, 2, 3, 4]) ) console.log( arrayToListLoop([1, 2, 3, 4]) )
 <script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>

The trick is to use two separate pointers for the list head and for the current node:

 function arrayToList(a) { var list = {}, p = list; for (let x of a) { p.value = x; p.rest = {}; p = p.rest; } return list; } console.log(arrayToList([11,22,33]))

To nullify the last pointer you're going to need three pointers:

function arrayToList(a) {
    var list = {}, p = list, q;
    for (let x of a) {
        p.value = x;
        p.rest = {};
        q = p;
        p = p.rest;
    }
    q.rest = null;
    return list;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM