【发布时间】:2016-03-19 15:38:08
【问题描述】:
我想通过随机插入字符来构建一个文本字符串,但是按顺序插入(作为一种效果)。到目前为止,我得到了:
// make a string and an array
var input = "Hello, world!",
output = [];
// split the string
input = input.split('');
我的想法是这样称呼它
function addAnElement(){
// check if there are any left
if(input.length){
// pick an element at random
var rand = Math.floor(Math.random() * input.length);
// remove it, so we don't call it again
var element = input.splice(rand,1);
// insert it
output[rand] = element;
// use the string returned as new innerHTML, for example
return output.join('');
// repeat until finished
setTimeout(addAnElement,5);
}
}
我希望这会返回如下内容:
'e'
'er'
...
'Hel, or!'
...
'Helo, Word!'
... and finally ...
'Hello, World!'
当然,问题在于数组在拼接时会重新索引 - 这会产生乱码。我认为答案必须是将元素链接到它们在input 中的位置,然后将它们原封不动地插入,必要时在返回之前按键排序。
我该怎么做?
【问题讨论】:
-
您可以保存第二个索引数组并在两个数组中进行拼接,然后从第二个数组获取索引
标签: javascript arrays