简体   繁体   English

我尝试使用 fisher-yates shuffle 字符串,但没有奏效

[英]I tried using a fisher-yates shuffle for strings, but it didn't work

I tried shuffling a string with a fisher-yates shuffle, but although it properly gets the indexes and the values, it doesn't shuffle the string, what is wrong?我尝试使用fisher-yates shuffle 对字符串进行改组,但是尽管它正确获取了索引和值,但它不会对字符串进行改组,有什么问题吗?

 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)

strings are immutable.字符串是不可变的。 Change placeHolder into an array 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)

Strings are immutable and you cannot mutate them.字符串是不可变的,你不能改变它们。 Read this for more information: https://stackoverflow.com/a/1431113/1128441阅读本文以获取更多信息: https://stackoverflow.com/a/1431113/1128441

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM