I have a big multidimensional array that holds references to objects and I need to be able to move a referen开发者_JS百科ce 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]
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:
- https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/delete_Operator
- http://www.openjs.com/articles/delete.php
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 ?
delete
doesn't delete the object, it deletes the property that was referencing the object. In your move
function, since you've just assigned that object to another property, you still have the object. (Whatever was previously in that slot in the array is toast, though.)
Your example above mostly works, here's an example (using a custom object so we can easily print out the contents of the arrays):
function T(id) {
this.id = id;
}
T.prototype.toString = function() {
return this.id;
};
var data = [[new T("0x0"), new T("0x1")],
[new T("1x0"), new T("1x1")]];
display("0: " + data[0].join(","));
display("1: " + data[1].join(","));
display("Moving 0x0 to 1x2");
move(0, 0, 1, 2);
display("0: " + data[0].join(","));
display("1: " + data[1].join(","));
function move(fromx, fromy, tox, toy) {
data[tox][toy] = data[fromx][fromy];
delete data[fromx][fromy];
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
Live copy
I wouldn't recommend delete
in this scenario, though, since it's very unlikely it's what you actually want. If you want to keep the "cell" but remove its contents, just assign undefined
to it. delete
actually removes it.
Somewhat off-topic, but: JavaScript doesn't have multi-dimensional arrays. What you have there is an array of arrays. It's a distinction that does actually have a difference, in that the arrays held by the outermost array can be of different lengths. (Also, JavaScript arrays are sparse — they're not really arrays at all, barring an implementation choosing to make them so — so the arrays could have the same length but gaps.)
精彩评论