簡體   English   中英

如何從jQuery中的數組中刪除選定的值?

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

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]);
    };
});

一旦我在循環中運行了最后一條命令,我便希望不再使用colorArray中的顏色。 我怎樣才能做到這一點?

工作小提琴

由於您使用的是jQuery

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

如果該項不在數組中。 好一點

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM