Home > other >  Can't overwrite javascript array
Can't overwrite javascript array

Time:02-17

I want to track changes of "results". If the results.length increases, the array will be overwritten and saved. If the length decreases, then the array will be overwritten, but the new value won't save.

playlists = [];
results = simpleMysqlQuery();
setinterval{
    update(playlists, results);
}

function update(playlists, results){
    if(playlists.length != results.length){
        playlists = reWritePlaylists(results, playlists);
    }
}

function reWritePlaylists(results, playlists){
   results.forEach(function(item, i, arr){
      playlists[i] = new Object();
      playlists[i]['id'] = results[i]['id'];
      playlists[i]['name'] = results[i]['name'];
   });
   if(playlists.length > results.length){
      playlists = playlists.slice(0, results.length);
   }
   return playlists;
}

CodePudding user response:

When you use slice and create a new array, the newly created array is no longer a reference to the original array, so the playlists parameter in update in no longer referring to the same array instance as the playlists variable outside the function. Try this:

playlists = [];
results = simpleMysqlQuery();
setinterval{
    playlists = update(playlists, results);
}

function update(playlists, results){
    if(playlists.length != results.length){
        playlists = reWritePlaylists(results, playlists);
    }
    return playlists
}

function reWritePlaylists(results, playlists){
   results.forEach(function(item, i, arr){
      playlists[i] = new Object();
      playlists[i]['id'] = results[i]['id'];
      playlists[i]['name'] = results[i]['name'];
   });
   if(playlists.length > results.length){
      playlists = playlists.slice(0, results.length);
   }
   return playlists;
}

CodePudding user response:

I found de wae!

function reWritePlaylists(results, playlists){
   playlists.splice(0, playlists.length);
   results.forEach(function(item, i, arr){
      playlists[i] = new Object();
      playlists[i]['id'] = results[i]['id'];
      playlists[i]['name'] = results[i]['name'];
   });
   return playlists;
}

CodePudding user response:

Please update reWritePlaylists function like below:

function reWritePlaylists(results, playlists){
   playlists.splice(0, results.length);
   results.forEach(function(item, i, arr){
      playlists[i] = new Object();
      playlists[i]['id'] = results[i]['id'];
      playlists[i]['name'] = results[i]['name'];
   });
   return playlists;
}

  • Related