如何在jQuery中随机删除或删除数组值?

时间:2011-04-20 09:31:24

标签: javascript jquery

如何在jQuery中删除数组中的值?

var prodCode = ["001","002","003","004","005","006","007","008"];

3 个答案:

答案 0 :(得分:12)

希望我的问题是正确的:您想要删除数组中的单个元素

var index = $.inArray(value, array);
if (index >= 0) {
   array.splice(index, 1);
}

,否则

$.each(arrayWithValuesToRemove, function (index, element) {
   var index = $.inArray(element, array);
   if (index < 0) {
      return;
   }
   array.splice(index, 1);
});

如果你只想随意删除

var desiredIndex = Math.floor(Math.random() * array.length);
array.splice(desiredIndex, 1);

如果你想保留索引,但不是它的值(与任何上面的例子结合):

delete array[index];

如果你想编写自己的比较方法(例如,对象作为值):

var compareFunction = function (element) {
    // TODO your compare stuff
};
var getIndexFunction = function (array) {
    for (var i = 0; i < array.length; i++) {
        var element = array[i];
        if (compareMethod(element)) {
            return i;
        }
    }
    return -1;
};
var index = getIndexFunction(myArray);
if (index >= 0) {
    myArray.splice(index, 1);
}

答案 1 :(得分:2)

我不确定我是否正确地提出了你的问题,但是如果你想删除数组中间的随机元素,你可以

array.splice(Math.floor(Math.random() * array.length), 1);

答案 2 :(得分:2)

var prodCode = ["001","002","003","004","005","006","007","008"];
var randomElementIndex = Math.floor( Math.random() * prodCode.length );
var removedElement = prodCode.splice(randomElementIndex, 1);
console.log(prodCode); //doesn't have removedElement with the index randomElementIndex anymore

从数组中删除随机元素。