views:

42

answers:

3

I have a big multidimensional array that holds references to objects and I need to be able to move a reference from one spot in the array to another and then delete the original reference (or set it to undefined). The problem with this is it then deletes the recent reference.

var data = [[new Obj, new Obj], [new Obj, new Obj]];

function move(fromx, fromy, tox, toy) {
   data[tox][toy] = data[fromx][fromy];
   delete data[fromx][fromy];
}

Edit: I mean both are gone. data[tox][toy] === undefined; Both references are destroyed, not just data[fromx][fromy]

+1  A: 

Yeah, that's just the delete operator doing what it is supposed to do, which is delete the object which is referred to at [fromx,fromy]. Try simply setting data[fromx][fromy] to null or an undefined variable such as allYourBaseBelongToUs (At least I'd hope it's undefined) or if you're boring undefined is also undefined.

Sources:

  1. https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/delete_Operator
  2. http://www.openjs.com/articles/delete.php
Andrew Dunn
Or, you know...`undefined`. ;-)
T.J. Crowder
I find using pop/code culture references as undefined variables is much more amusing though.
Andrew Dunn
A: 
var x = [[{'a':'1'}, {'b':'1'}], [{'c':'1'}, {'d':'1'}]]
x[1][0] = x[0][0]
x[1][1] = x[0][1]
delete x[0][0]
delete x[0][1]

console.log(x)

prints [[undefined, undefined], [Object { a="1"}, Object { b="1"}]]

What's your expected output ?

letronje
A: 
T.J. Crowder