Array.prototype.remove = function(v) { this.splice(this.indexOf(v) == -1 ? this.length : this.indexOf(v), 1); }
var a = ['a','b','c'];
a.remove('c'); //value of "a" is now ['a','b']
//in case somebody needs something like this: multidimensional array (two items)
var ar = [[0,'a'],[1,'b'],[2,'c'],[3,'d'],[4,'e'],[5,'f']];
var removeItem = 3;
ar = jQuery.grep(ar, function(n) {
return n[0] != removeItem; //or n[1] for second item in two item array
});
ar;
//This prototype function allows you to remove even array from array
Array.prototype.remove = function(x) {
var i;
for(i in this){
if(this[i].toString() == x.toString()){
this.splice(i,1)
}
}
}
使用实例
var arr = [1,2,[1,1], 'abc'];
arr.remove([1,1]);
console.log(arr) //[1, 2, 'abc']
var arr = [1,2,[1,1], 'abc'];
arr.remove(1);
console.log(arr) //[2, [1,1], 'abc']
var arr = [1,2,[1,1], 'abc'];
arr.remove('abc');
console.log(arr) //[1, 2, [1,1]]
/** SUBTRACT ARRAYS **/
function subtractarrays(array1, array2){
var difference = [];
for( var i = 0; i < array1.length; i++ ) {
if( $.inArray( array1[i], array2 ) == -1 ) {
difference.push(array1[i]);
}
}
return difference;
}
然后可以在代码中的任何地方调用该函数。
var I_like = ["love", "sex", "food"];
var she_likes = ["love", "food"];
alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty :P"!
// Define polyfill for browsers that don't natively support Array.indexOf()
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this===null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this),
len = O.length >>> 0;
if (len===0) return -1;
var n = +fromIndex || 0;
if (Math.abs(n)===Infinity) n = 0;
if (n >= len) return -1;
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in O && O[k]===searchElement) return k;
++k;
}
return -1;
};
}
// Remove first instance of 2 from array
if (y.indexOf(2) > -1) {
y.splice(y.indexOf(2), 1);
}
/* To remove all instances of 2 from array, change 'if' to 'while':
while (y.indexOf(2) > -1) {
y.splice(y.indexOf(2), 1);
}
*/
console.log(y); // Returns [1, 3]
var x = [1,2,3,4,5,4,4,6,7];
var item = 4;
var startItemIndex = $.inArray(item, x);
var itemsFound = x.filter(function(elem){
return elem == item;
}).length;
或
var itemsFound = $.grep(x, function (elem) {
return elem == item;
}).length;
var x = [1, 2, "bye", 3, 4];
var y = [1, 2, 3, 4];
var removeItem = "bye";
// Removing an item that exists in array
x.splice( $.inArray(removeItem,x), $.inArray(removeItem,x) ); // This is the one-liner used
// Removing an item that DOESN'T exist in array
y.splice( $.inArray(removeItem,y), $.inArray(removeItem,y) ); // Same usage, different array
// OUTPUT -- both cases are expected to be [1,2,3,4]
alert(x + '\n' + y);