简体   繁体   中英

Looping through types in an object

Ok so yesterday I asked a question, and I was able to solve this problem, but after retrying it today I can't really understand why what I did on my own isn't working. My question is basically, why when I log this, is it skipping the first element of my array ( the 20 value). My guess is that the 30 is overwriting the previous spot, but I can't really make sense of why . Here is my though on things

First our list is value:10, rest:null now i =1, so we will add a value of 20 and another rest:null to the pre-existing rest . thus get value:10, rest: value:20, rest:null , and then the same for the value of 30.

function arrayToList(array)
{
    var list = {value : array[0], rest: null } ;
    for ( i =  1 ; i<array.length ; i++)
        {
           list.rest = { value: array[i], rest:null} 

        }
    return list;
}

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

You are overwriting the value of rest with each of your traversal. I think you should use concept of recursive function to make it fast and accurate.

Please use the following code:

function arrayToList(array, i){
    if(i == array.length){
        return null ;
    }
    return { value: array[i], rest: arrayToList(array, i+1) };
}
console.log(arrayToList([10,20,30], 0));

Here, i represents the index in array. I hope this solves your problem. It worked fine at my system.

The result I got is:

{
    value: 10, 
    rest: {
        value: 20, 
        rest: {
            value: 30, 
            rest:null
        }
    }
}

Good Luck!!!!

I guess you want to add remaining values to rest . If so you should declare it as an array instead of null

function arrayToList(array) {
    var list = { value: array[0], rest: [] };
    for(i = 1; i < array.length; i++) {
        list.rest.push({ value: array[i], rest: null });
    }
    return list;
}

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

The above code will return this object

{
  value: 10,
  rest: [
    { value: 20, rest: null },
    { value: 30, rest: null }
  ]
}

because you start with i=1, it should be i=0. Arrays are 0-based in JavaScript (and basically every other language).

My guess is that the 30 is overwriting the previous spot

that's right. You are overwriting list.rest property on each loop iteration. So, in the end the value property will be filled with the last array value 30

Recursive solution is recommended :

function arrayToList(array, i){
    if(!i){i=0;}
    if(i == array.length){
        return null ;
    }
    return { value: array[i], rest: arrayToList(array, i+1) };
}

Then :

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

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