简体   繁体   English

如何从jQuery中的数组中删除选定的值?

[英]How to remove a selected value from an array in jQuery?

jsfiddle jsfiddle

$(document).ready(function() {
    var colorArray = new Array(
      "#ff0000",
      "#000000",
      "#00ff00",
      "#0000ff"
    );

    var randColor, randListElem;
    var listElems = $('li');

    for(var i = 0; i < 3; i++)
    {
        //randColor = Math.floor(Math.random()*(colorArray.length));
        colorArray.sort(function() { return 0.5 - Math.random();});
        var ran = colorArray.pop();
        randListElem = Math.floor(Math.random()*(listElems.length));
        $(listElems[randListElem]).css("background", colorArray[ran]);
    };
});

Once I run the last command in the loop I want to remove the color in colorArray from being used again. 一旦我在循环中运行了最后一条命令,我便希望不再使用colorArray中的颜色。 How can I do this? 我怎样才能做到这一点?

Working Fiddle 工作小提琴

Since you're using jQuery 由于您使用的是jQuery

colorArray.splice($.inArray(randColor, myarray), 1);

If the item isn't in the array. 如果该项不在数组中。 Something a little better 好一点

var index = $.inArray(randColor, colorArray);
if (index>=0) colorArray.splice(index, 1);

Or 要么

var itemtoRemove = randcolor;
arr.splice($.inArray(itemtoRemove, colorArray),1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM