JS array toggle push & splice
I have what I thought will be a simple task of 'toggling' a value to an array.
What I want to do is to add the row if it doesn't exist and delete if it does exist:
selected = new Array();
// repeated code
if(row in selected===true) selected.splice(row);
else selected.push(row);
Now this works fine with the exception of the first element in the array, which always remains unchanged and is apparently not recognized by the "in selected".
a) row = 1 > ["开发者_JAVA技巧1"]
b) row = 1 > ["1", "1"]
c) row = 2 > ["1", "1", "2"]
d) row = 2 > ["1", "1"]
e) row = 1 > ["1"]
f) row = 1 > ["1", "1"]
using the values and output above you can see that "1" gets added as the first element and never removed ??
the in operator and the slice method both take an index, not a value. i.e. rows = ["1", "2"]
would be better expressed as
rows = []
rows[0] = "1";
rows[1] = "2";
so in the above example, 0 in rows
returns true, because rows[0]
exists.
Or, in your case, when rows = ["1"]
, 1 in rows
returns false, because rows[1]
does not exist.
Then when rows = ["1", "1"]
, 1 in rows
returns true because rows[1]
exists, so you then remove it. etc etc.
instead of arrays and pushes, you could try just using objects....
var rows = {}
...
if(rows[selected]){
rows[selected] = selected;
}
else{
rows[selected] = null;
}
精彩评论