javascript 如果字符串中有多个占位符,如何用不同的值替换占位符?

whhtz7ly  于 2022-12-25  发布在  Java
关注(0)|答案(3)|浏览(164)
arr = [1,2,3,4,5,6,7]
val = ? (3 different values from arr)
result = "${val} and ${val} and ${val}"

我想将${瓦尔}替换为arr元素,以便${val}在结果中不相同。
我真的不知道如何替换不同的值来代替${val}

7xllpg7q

7xllpg7q1#

另一个想法是使val成为返回arr元素的函数。
我使用了一个tempArr来避免改变原来的arr
当没有更多的值可供使用时...它将返回?

const arr = [1, 2, 3, 4, 5, 6, 7];
let tempArr = [...arr]

val = () => {
  
  if(!tempArr.length){
    return '?'
  }
  const randomIndex = Math.floor(Math.random() * tempArr.length)
  const arrElement=  tempArr[randomIndex];
  tempArr.splice(randomIndex, 1)
  
  return arrElement
};

console.log(`${val()} and ${val()} and ${val()}`);
console.log(`${val()} and ${val()} and ${val()}`);
console.log(`${val()} and ${val()} and ${val()}`);
cczfrluj

cczfrluj2#

我的方法是:
使用带标记的模板文本更改参数的处理以满足您的需要。
你的问题中的?val = ?)只是一个使用[...arr]的数组的副本,然后,tag函数将调用一个randomElement函数,这个函数将随机地从数组中移除并返回一个元素。

function randomElement(array) {
  if (!array) return array;
  return array.splice(Math.floor(Math.random() * array.length), 1);
}

function rand(strings, ...args) {
  const parts = [];
  for (let string of strings) {
    parts.push(string, randomElement(args.shift()));
  }
  return parts.join('');
}

arr = [1, 2, 3, 4, 5, 6, 7]
val = [...arr]
result = rand`${val} and ${val} and ${val}`
console.log(result);
bvk5enib

bvk5enib3#

你可能要找的是数组洗牌,这个线程包含了一些有用的函数:https://stackoverflow.com/a/2450976/13199472(就我个人而言,我喜欢使用Durstenfeld shuffle算法的ES6变体,这是该线程中的第二个答案)。
使用shuffle函数时,代码应如下所示:

arr = [1,2,3,4,5,6,7]
shuffle(arr)
result = `${arr[0]} and ${arr[1]} and ${arr[2]}`

不需要单独的变量。但是,由于您提到您的数据集包含的字符串中的模板标记具有相同的名称,一个可能的解决方案是不将字符串视为JavaScript模板文字,而是将其视为普通字符串,您将在其中单独替换标记。

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
}

String.prototype.replace只会替换所提供字符串的第一个匹配项,因此这种方法允许您使用混洗数组中的项逐个替换每个标记。

相关问题