为什么我在使用我的函数时得到 [native code]

why i get [native code] when use my function

我正在尝试创建一个函数来反转字符串的字母大小写,因此字符串 "John" 将是 "jOHN".

这是我的代码:

const upperLower = function(string){
  let newString ="", newChar ="";

  for(let i = 0; i < string.length; i++){
    if (string.charAt(i) === " "){
      newChar = " "
    } else if (string.charAt(i) === string.charAt(i).toUpperCase()){
      newChar = string.charAt(i).toLowerCase;
    } else {
      newChar = string.charAt(i).toUpperCase;
    }
    newString += newChar;
  }
  return newString;
}

当我使用它时,我得到的是这样的:

"function toLowerCase() { [native code] }function toUpperCase() { [native code] }function toUpperCase() { [native code] }function toUpperCase() { [native code] } function toLowerCase() { [native code] }function toUpperCase() { [native code] }function toUpperCase() { [native code] }function toUpperCase() { [native code] }function toUpperCase() { [native code] }function toLowerCase() { [native code] }"

我哪里错了,为什么我的结果看起来像那样?谢谢

您实际上并没有在 else 条件下调用 toLowerCasetoUpperCase。您正在引用它们,因此您获得了函数的默认字符串表示形式。

{newChar = string.charAt(i).toLowerCase}      // <=- Not calling
else {newChar = string.charAt(i).toUpperCase} // <=- Not calling

您需要 () 才能实际调用该函数,就像您使用 toUpperCase() 一样。

无关,但您的代码格式使其难以阅读。

读起来更容易,调试和思考也更容易。如果一切都不是一团糟,错误将非常清楚。

const upperLower = function(string){
  let newString ="", newChar ="";
  for (let i=0; i < string.length; i++) {
    if (string.charAt(i) === " ") {
      newChar = " "
    } else if (string.charAt(i) === string.charAt(i).toUpperCase()) {
      newChar = string.charAt(i).toLowerCase()
    } else {
      newChar = string.charAt(i).toUpperCase()
    }
   newString += newChar;
  }

  return newString;
}

console.log(upperLower("hELLO"));