我尝试用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)
答案 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);
}