简体   繁体   中英

JavaScript array splice

Hello StackOverflow community!

At the moment I am completly stuck with my code, have try different ways to remove a value from array when picked, I know I have to use splice for it, but for some reason it is not doing what I want it to do

Since the web page is quite difficult to explain as my english aint that good, I have made some screenshots of it, I hope you will get the idea when you see what I want to do!

This is what the user will see when he visit the webpage, it's basicly a lenormand game. the user has to drag 3 cards in to the gray box below the cards.

Once he has dragged 3 cards to the box, the user can click on the images (Cards) to turn them (flip)

This works fine, the only problem is that I don't want the user to pick the same cards twice of even three times, Since I do this with a array, I thought I should use Splice function, but so far, no result!

for the JavaScript code, here is the JSFiddle http://jsfiddle.net/dkk2nqyg/

Somewhere here, I must add the splice

$(function () {
var cars = ["2", "3", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "4"];
var rand = cars[Math.floor(Math.random()*cars.length)];

    $(".cards img").each(function(index) {
        $(this).wrap('<div class="front"></div>')
           .parent().wrap('<div class="flipper"></div>')
           .parent().wrap('<div class="flip-container"></div>')
           .append('<div class="back"><img src="./kaart/'+cars[Math.floor(Math.random()*cars.length)]+'.png"</img> </div>');
});

I have try'd many solutions, but the problem is that I need to splice it here, atleast, I think:

.append('<div class="back"><img src="./kaart/'+cars[Math.floor(Math.random()*cars.length)]+'.png"</img> </div>');

I would gladly have this issue resolved and I hope StackOverflow can offer me the help I want :)

Thanks!

First, put the random-number in a seperate variable

var rnd = Math.floor(Math.random()*cars.length);
var rand = cars[rnd];

Then remove that specific item from the array

cars.splice(rnd, 1);

Cheers R

您可以使用splice()从数组中删除一项,因为splice返回一个数组,然后您可以访问索引为0的元素以获取提取的src值

'<div class="back"><img src="./kaart/' + cars.splice(Math.floor(Math.random() * cars.length),1)[0] + '.png"</img> </div>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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