我试过用费舍尔·耶茨(Fisher-yates)洗牌作琴弦,但这没用

时间:2019-09-24 19:30:22

标签: javascript shuffle

我尝试用fisher-yates混洗对字符串进行混洗,但是尽管它可以正确地获取索引和值,但不能对字符串进行混洗,这是怎么回事?

globalVar = 'I am GLOBAL'

function scrambler(anyString) {
  let placeHolder = anyString
  for (let i = placeHolder.length - 1; i >= 0; i--) {
    let swapIndex = Math.floor(Math.random() * (i + 1))
    let chartoSwap = placeHolder[swapIndex]
    let currentChar = placeHolder[i]
    placeHolder[i] = chartoSwap
    placeHolder[swapIndex] = currentChar
  }
  return placeHolder
}

let scrambled = scrambler(globalVar)
console.log(scrambled)

2 个答案:

答案 0 :(得分:4)

字符串是不可变的。将placeHolder更改为数组

globalVar = 'I am GLOBAL'

function scrambler(anyString) {
  let placeHolder = anyString.split("")
  for (let i = placeHolder.length - 1; i >= 0; i--) {
    let swapIndex = Math.floor(Math.random() * (i + 1))
    let chartoSwap = placeHolder[swapIndex]
    let currentChar = placeHolder[i]
    placeHolder[i] = chartoSwap
    placeHolder[swapIndex] = currentChar
  }
  return placeHolder.join("")
}

let scrambled = scrambler(globalVar)
console.log(scrambled)

答案 1 :(得分:1)

字符串是不可变的,您不能对其进行突变。请阅读以下内容以获取更多信息:https://stackoverflow.com/a/1431113/1128441

String.prototype.replaceAt=function(index, replacement) {
  return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}