鍍金池/ 問答/HTML/ 在函數內部改了參數,再用return返回參數,卻顯示原始輸入的參數,該怎么辦?

在函數內部改了參數,再用return返回參數,卻顯示原始輸入的參數,該怎么辦?

clipboard.png
剛接觸javascript幾個禮拜,碰到一個關于凱撒密碼的問題,就動手寫了一下,自己還沒寫完。發(fā)現函數內部雖然對參數做了變動,但想返回已經變動過的參數(達到字母移位的效果),卻返回了原封不動的原參數,該怎么辦?

回答
編輯回答
厭遇
  1. 代碼第九行不要使用inin用于判斷一個對象有沒有一個屬性,不能判斷一個數組是否包含某個元素,使用includes代替;
  2. 代碼第10行使用str = str.replace重新給str賦值;
function rot13 (str) {
  var empty = [];
  for (var i = 0; i < str.length; i++) {
    empty.push(str.charCodeAt(i))
  }
  var left = empty.filter(function (x) {return x >= 65 && x <= 77})
  var right = empty.filter(function (y) {return y >= 78 && y <= 90})
  for (var j = 0; j < str.length; j++) {
    if (left.includes(str.charCodeAt(j))) { // 使用includes
      str = str.replace(str[j], String.fromCharCode(str.charCodeAt(j) + 13)) // 重新賦值
    }
  }
  return str
}
2017年9月11日 10:41
編輯回答
膽怯

str進行replace之后,要把得到的內容重新賦回給str

2018年4月21日 15:00
編輯回答
夢一場
str = str.replace...

其實, 沒必要在charCodeAt/fromCharCode之間轉來轉去的, 完全可以處理完統(tǒng)一轉

function rot13(str){
    // 將 字符串 轉為 Unicode值數組
    var empty = Array.prototype.map.call(str,function(s){return s.charCodeAt(0)})
    // 構建一個新數組
    .map(function(num){
        // left
        if(num >=65 && num <= 77){
            return num + 13;
        // right
        } else if(num >= 78 && num <= 90){
            return num;
        // 其它
        } else {
            return num;
        }
    });
    // 將 Unicode值數組 轉回字符串
    return String.fromCharCode.apply(null, empty);
}
2017年3月5日 08:12