为 2 个数组获取相同的随机索引

Posted

技术标签:

【中文标题】为 2 个数组获取相同的随机索引【英文标题】:getting the same random index for 2 arrays 【发布时间】:2021-05-07 13:19:10 【问题描述】:

我正在构建一个抽认卡网络应用程序,我试图让一个随机的日文字符出现,但同时该字符也有英文值。

所以我有两个数组(一个英文和一个日文),我有,在这里有人的帮助下,我设法让随机的日文字母显示出来。

我的问题是如何在不破坏其余代码的情况下为英语数组获取相同的索引值以检查答案?

 // kana indexes 
var kanaArray = ["あ","い","う","え","お","か","き","く","け","こ","さ","し","す","せ","そ","た","ち","つ",
"て","と","な","に","ぬ","ね","の","は","ひ","ふ","へ","ほ","ま","み","む","め","も","や","ゆ","よ","ら","り","る",
"れ","ろ","わ","を","ん"]

var kanaEng = ["a","i","u","e","o","ka","ki","ku","ke","ko","sa","shi","su","se","so","ta","chi","tsu",
"te","to","na","ni","nu","ne","no","ha","hi","fu","he","ho","ma","mi","mu","me","mo","ya","yu","yo","ra","ri","ru",
"re","ro","wa","wo","n"]

let getRandomKana = () => kanaArray[Math.floor(Math.random()*kanaArray.length-1)];

let getAnswerVal = kanaEng[Math.floor(Math.random()*kanaEng.length-1)];

//logic

var started = false;
var level = 0;
let kanaPassed = [];

// start and switch buttons 
$(document).ready(function()
    $(".startBtn").click(function()
        started = true
        $('.startBtn').css("visibility", 'hidden');
        $('.switchBtn').css("visibility", 'visible');
        $('h3').text(getRandomKana());
        $('h3').css("visibility",'visible');
        console.log(started)
    )
);

$('.switchBtn').click(function()
    $('h3').text(getRandomKana());
);

// check answer 
$('.submit').click(function()
    console.log(getAnswerVal);
    if($('#answerBox').val()===getAnswerVal)
        $('card').css('background-color','red');
    
);

【问题讨论】:

... 将索引存储在某处? 将索引存储在变量中:) 或者使用更适应的数据结构... "あ":"a", "い":"i", "う":"u" 【参考方案1】:

您可以确保获取第一个数组索引并在第二个数组上使用相同的索引,以便获得相同的翻译。有些是这样的:

const kanaArray = ["あ","い","う","え","お","か","き","く","け","こ","さ","し","す","せ","そ","た","ち","つ","て","と","な","に","ぬ","ね","の","は","ひ","ふ","へ","ほ","ま","み","む","め","も","や","ゆ","よ","ら","り","る","れ","ろ","わ","を","ん"];

const kanaEng = ["a","i","u","e","o","ka","ki","ku","ke","ko","sa","shi","su","se","so","ta","chi","tsu","te","to","na","ni","nu","ne","no","ha","hi","fu","he","ho","ma","mi","mu","me","mo","ya","yu","yo","ra","ri","ru","re","ro","wa","wo","n"];

const randomIndex = Math.floor(Math.random()*kanaArray.length);
const randomKanaArray = kanaArray[randomIndex];
const randomKanaEng  = kanaEng[randomIndex];

如果你用 JSON obj 存储它,你可以更容易:

const KANAS = [jap: "あ", eng: "a",...];
const RANDOM_KANAS= KANAS[Math.floor(Math.random()*KANAS.length)];
console.log(RANDOM_KANAS.jap, RANDOM_KANAS.eng);

【讨论】:

嘿,所以你所说的在某种程度上有所帮助,但它并没有给我一个英文版的随机值。这是我将随机值存储在索引中时遇到的问题,它似乎在两者上都不匹配。 嘿@Co​​dechunk 你能解释一下你在上面编辑它的问题中究竟在寻找什么吗?

以上是关于为 2 个数组获取相同的随机索引的主要内容,如果未能解决你的问题,请参考以下文章

在 Python 中随机交错 2 个数组

2个数组随机显示1-10和随机1-10无功能

怎么用python生成随机的且不重复的整数?

jAVA如何使一个数组里面的元素随机交换位置

JS从数组中随机取出几个数组元素的方法

IDL 中 如何从一个数组中随机取出3个数?