if (!Array.prototype.removeArr) {Array.prototype.removeArr = function(arr) {if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!var that = this;if(arr.length){var i=0;while(i<that.length){if(arr.indexOf(that[i])>-1){that.splice(i,1);}else i++;}}return that;}}
function wantDelete(item, arr){for (var i=0;i<arr.length;i++){if (arr[i]==item){arr.splice(i,1); //this delete from the "i" index in the array to the "1" lengthbreak;}}}var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']
/*** @param {Array} array the original array with all items* @param {any} item the time you want to remove* @returns {Array} a new Array without the item*/var removeItemFromArray = function(array, item){/* assign a empty array */var tmp = [];/* loop over all array items */for(var index in array){if(array[index] !== item){/* push to temporary array if not like item */tmp.push(array[index]);}}/* return the temporary array */return tmp;}
function removeArrayValue(array, value){var thisArray = array.slice(0); // copy the array so method is non-destructive
var idx = thisArray.indexOf(value); // initialise idx
while(idx != -1){thisArray.splice(idx, 1); // chop out element at idx
idx = thisArray.indexOf(value); // look for next ocurrence of 'value'}
return thisArray;}
function removeFrmArr(array, element) {return array.filter(e => e !== element);};var exampleArray = [1,2,3,4,5];removeFrmArr(exampleArray, 3);// return value like this//[1, 2, 4, 5]
您可以使用plice从数组中删除单个元素,但plice不能从数组中删除多个类似的元素。
function singleArrayRemove(array, value){var index = array.indexOf(value);if (index > -1) array.splice(index, 1);return array;}var exampleArray = [1,2,3,4,5,5];singleArrayRemove(exampleArray, 5);// return value like this//[1, 2, 3, 4, 5]
var ary = ['three', 'seven', 'eleven'];var index = ary.indexOf(item);//item: the value which you want to remove
//Method 1ary.splice(index,1);
//Method 2delete ary[index]; //in this method the deleted element will be undefined
var ary = ['three', 'seven', 'eleven'];var index = ary.indexOf('seven'); // get index if value found otherwise -1
if (index > -1) { //if foundary.splice(index, 1);}
方法2
单线解决方案
var ary = ['three', 'seven', 'eleven'];filteredArr = ary.filter(function(v) { return v !== 'seven' })
// Or using ECMA6:filteredArr = ary.filter(v => v !== 'seven')