改组多个数组Javascript [英] Shuffling Multiple arrays Javascript
问题描述
我需要使用相同的函数对多个数组进行混洗,以便将每个句子中的单词随机化.
I need to shuffle multiple arrays using the same function so that it randomizes the words up in each sentence.
然后使用HTML,我需要一个按钮来开始随机播放,输出的句子之间会有换行符,例如:
Using HTML i then need a button that starts the shuffle, with the outputted sentences with line break between each for example:
var array1 = ["The, "Man", "and", "his", "dog"];
var array2 = ["went", "for", "a", "walk", "outside"];
在单击随机播放"按钮时,我试图使输出显示在单独的行上,如下所示:
On click of a button "shuffle" im trying to get the output to display on seperate lines like this:
男人和狗狗的
去户外散步
谢谢
推荐答案
您应使用map
和sort
方法.
首先,可以使用Math.random
方法为数组中的每个项目生成一个随机数.下一步是按此generated
号对数组进行排序.
First of all, you can generate a random number for every item in the array, using Math.random
method. Next step is to sort array by this generated
number.
最后一步是使用join
方法创建包含数组项的句子.
Last step is to create the sentence with the items of the array, using join
method.
var array1 = ["The", "Man", "and", "his", "dog"];
console.log(array1.map(function(n){
return [Math.random(), n];
}).sort().map(function(item){
return item[1] ;
}).join(' '));
这篇关于改组多个数组Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!