简体   繁体   English

JavaScript数组拼接

[英]JavaScript array splice

Hello StackOverflow community! 您好StackOverflow社区!

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 目前,我完全陷入了代码困境,尝试了各种不同的方法来从数组中删除值(在选择时),我知道我必须为此使用splice,但是由于某种原因,它没有按照我想要的去做

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. 用户必须将3张卡片拖到卡片下方的灰色框中。

Once he has dragged 3 cards to the box, the user can click on the images (Cards) to turn them (flip) 将3张卡片拖到框中后,用户可以单击图像(卡片)以将其翻转(翻转)

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! 这很好用,唯一的问题是我不希望用户选择同一张卡片,甚至两次,甚至两次。由于我是用数组进行的,所以我认为我应该使用Splice函数,但到目前为止,没有结果!

for the JavaScript code, here is the JSFiddle http://jsfiddle.net/dkk2nqyg/ 有关JavaScript代码的信息,请参见以下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 :) 我很高兴能解决此问题,希望StackOverflow可以为我提供我想要的帮助:)

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 干杯R

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

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

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

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