Reputation: 15369
I found this function on the john resig blog for removing an element from an array. It works really well! but I don't really understand how..
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
I'm confused about what is happening with this statement: (to || from) + 1 || this.length)
for starters; perhaps once I understand that, the rest will become more clear. Any help sussing out exactly what's happening here is much appreciated. Thanks.
Upvotes: 1
Views: 131
Reputation: 225074
The first part gets the rest of the array, after the slice. If you specify a to
, it slice
s everything after the to
; otherwise, it slice
s everything after from
. If either of those were -1
, it gets an empty slice.
The next part truncates the array to right before the starting position of the removal.
The last part re-inserts the rest
(the part after the range to be removed) at the end of the array.
Upvotes: 1
Reputation: 944011
If the left hand side of ||
is a true value, it will return the left hand side. Otherwise it will return the right hand side.
Upvotes: 0