let arr = [1,2,3,4,5,6,7]
shuffle(arr)
// notice how these are STRINGS, not template literals, they
// are inside single quotes, not backticks
// using backticks here will break your code
const template = '${val} and ${val} and ${val}'
const tagCount = template.split('${val}').length
let output = template;
for (let i = 0; i < tagCount; i++) {
output = output.replace('${val}', arr[i])
// you can take arr[i % arr.length] instead of arr[i]
// in case you have more tags than items in the array, but
// this will obviously result in duplications
}
3条答案
按热度按时间7xllpg7q1#
另一个想法是使
val
成为返回arr
元素的函数。我使用了一个
tempArr
来避免改变原来的arr
。当没有更多的值可供使用时...它将返回
?
。cczfrluj2#
我的方法是:
使用带标记的模板文本更改参数的处理以满足您的需要。
你的问题中的
?
(val = ?
)只是一个使用[...arr]
的数组的副本,然后,tag函数将调用一个randomElement
函数,这个函数将随机地从数组中移除并返回一个元素。bvk5enib3#
你可能要找的是数组洗牌,这个线程包含了一些有用的函数:https://stackoverflow.com/a/2450976/13199472(就我个人而言,我喜欢使用Durstenfeld shuffle算法的ES6变体,这是该线程中的第二个答案)。
使用shuffle函数时,代码应如下所示:
不需要单独的变量。但是,由于您提到您的数据集包含的字符串中的模板标记具有相同的名称,一个可能的解决方案是不将字符串视为JavaScript模板文字,而是将其视为普通字符串,您将在其中单独替换标记。
String.prototype.replace
只会替换所提供字符串的第一个匹配项,因此这种方法允许您使用混洗数组中的项逐个替换每个标记。