简体   繁体   English

在 keydown 时从数组返回非重复随机项

[英]Return non-repeating random item from array on keydown

 var myArray = [ ["a", "a1", "a2", "a3"] //["b", "b1", "b2", "b3"], //["c", "c1", "c2", "c3"] ]; function getRandom(arr) { if (arr.length === 0) { return arr } var a = Math.floor(Math.random() * arr.length); var b = arr.splice(a, 1); console.log(b[0]) return b[0]; } function compare(entry, string) { for (var x in entry) { array1 = entry[x][0].split(' '); if (array1.includes(string)) { items = entry[x].slice(1); return getRandom(items) } } } $("#input").keydown(function(e) { keyword = $(this).val(); if (e.which === 13) { $(this).val(""); text = keyword.toLowerCase(); result = '<div>' + compare(myArray, text) + '</div>' $('#results').append(result); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="input" type="text" placeholder="Search..." autocomplete="off" /> <div id="results" class="reset">

getRandom function should get random item, return and remove that item, then restart the process when the original array is equal to zero but it's not working... getRandom函数应该获取随机项目,返回并删除该项目,然后在原始数组等于零时重新启动该过程但它不起作用......

To test, enter a into input box.要测试,请在输入框中输入a The result I need should be a1, a2, and a3 one at a time in random order for the first three attempts then restart the process.我需要的结果应该是a1, a2, and a3 ,在前三次尝试中以随机顺序一次一个,然后重新启动该过程。 Thanks for your help!谢谢你的帮助!

The problem is that you pass items to getRandom, which is the function that alters its argument ... but items is created using the slice method, which creates a brand new array (in fact, one way to make an exact copy of an array that we can change without affecting the original is is arr.slice() ).问题是,你通过items来getRandom,这是改变其参数的函数...但items使用创建slice的方法,这将创建一个全新的阵列(事实上,一个方法,使一个阵列的精确拷贝我们可以在不影响原来的情况下更改的是arr.slice() )。 So the changes made by getRandom will not alter myArray .因此getRandom所做的更改不会改变myArray

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

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