如何在javascript中使用textarea改写数字 [英] how to shuffle numbers with textarea in javascript
问题描述
如果我将数字这样输入文本区域:
If I put numbers into a textarea like so:
418484
418485
418486
我希望他们被改组,并且我想要这样的输出:
I want them to get shuffled, and I want an output like this:
418485
418484
418486
我不希望更改值-我只想要一些JavaScript或jQuery,它们可以将这些数字改组并在网页上显示结果.
I don't want the values changed - I just want some JavaScript or jQuery that will shuffle these numbers and give me the result in my web page.
推荐答案
我从此答案中发现了一个很棒的随机播放功能:
I found this great shuffle function from this answer:
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
从那里,您可以简单地获取<textarea>
输入的值,并根据换行符对其进行分割:
From there, you can simply get the value of the <textarea>
's input, and split it based on linebreaks:
var numbers = document.getElementById("numberInput").value.split("\n");
或者,如果您喜欢空格:
Or if you prefer spaces:
var numbers = document.getElementById("numberInput").value.split(" ");
然后,将其传递给函数:
Then, just pass it into the function:
var shuffledNumbers = shuffle(numbers);
并通过遍历它们并将其写入文档的方式在页面上显示它们:
And show them on the page by iterating over them and writing them to the document:
shuffledNumbers.forEach(function(currentNumber) {
document.write(currentNumber + "<br />");
})
然后就可以了!
如果您想在另一个<textarea>
中显示改组的数字,则:
If you want to display the shuffled numbers in another <textarea>
instead:
var output = document.getElementById("output");
shuffledNumbers.forEach(function(currentNumber) {
output.innerHTML += currentNumber + "\n";
})
这篇关于如何在javascript中使用textarea改写数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!