0

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 > ["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 ??

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note that my object solution won't preserve the order of the elements, will only check if they're set or not. If you wan to maintain order, you'll have to loop and scoop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.