-
2
- #1
i don't think equivalent functions exist in core js, so i created these for convenience:
use them like so:
[tt]
var array1 = [0,1,2,3,4];
alert("pull(2) returns: " + array1.pull(2));
alert("array1 now == [" + array1 + "]"
alert("insert(2,2) returns: " + array1.insert(2,2));
alert("replace(2, \"two\" returns: " + array1.replace(2, "two");
[/tt]
=========================================================
while (!succeed) try();
-jeff
Code:
Array.prototype.pull = function (arg) {
// pulls an element out of an array, returns the single element.
// array.length becomes one less.
// may pass the index or value of element to remove
var oEl, tmp;
if (typeof arg == "number") {
oEl = this[arg];
tmp = this.slice(0,arg).concat(this.slice(arg + 1));
}
else if (typeof arg == "string") {
for (var x = 0; x < this.length; x++) {
if (this[x] == arg) {
oEl = this[x];
tmp = this.slice(0,x).concat(this.slice(x + 1));
break;
}
}
}
if (typeof oEl != "undefined") {
this.length = 0;
for (var x = 0; x < tmp.length; x++)
this[x] = tmp[x];
return oEl;
}
else return null;
}
Array.prototype.replace = function (id, val) {
// replaces the element in Array at index "id" with value "val"
var tmp = this.slice(0,id).concat(val, this.slice(id+1));
this.length = 0;
for (var x = 0; x < tmp.length; x++) {
this[x] = tmp[x];
}
return this;
}
Array.prototype.insert = function (id, val) {
// inserts value "val" into Array at index "id"
// Array.length increases by one
tmp = this.slice(0,id).concat(val,this.slice(id));
this.length = 0;
for (var x = 0; x < tmp.length; x++) {
this[x] = tmp[x];
}
return this;
}
use them like so:
[tt]
var array1 = [0,1,2,3,4];
alert("pull(2) returns: " + array1.pull(2));
alert("array1 now == [" + array1 + "]"
alert("insert(2,2) returns: " + array1.insert(2,2));
alert("replace(2, \"two\" returns: " + array1.replace(2, "two");
[/tt]
=========================================================
while (!succeed) try();
-jeff