[英]JS array toggle push & splice
我以為將值“切換”到數組將是一個簡單的任務。
我想做的是添加行(如果不存在),然后刪除(如果存在):
selected = new Array();
// repeated code
if(row in selected===true) selected.splice(row);
else selected.push(row);
現在,除了數組中的第一個元素(該元素始終保持不變,並且顯然未被“ 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"]
使用上面的值和輸出,您可以看到“ 1”被添加為第一個元素並且從未刪除?
in運算符和slice方法都采用索引,而不是值。 即rows = ["1", "2"]
最好表示為
rows = []
rows[0] = "1";
rows[1] = "2";
因此在上面的示例中, 0 in rows
返回true,因為存在rows[0]
。
或者,在您的情況下,當rows = ["1"]
, 1 in rows
返回false,因為rows[1]
不存在。 然后,當rows = ["1", "1"]
, 1 in rows
返回true,因為存在rows[1]
,因此您將其刪除。 等等等
而不是數組和推入,您可以嘗試僅使用對象。
var rows = {}
...
if(rows[selected]){
rows[selected] = selected;
}
else{
rows[selected] = null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.