【问题标题】:why i get [native code] when use my function [duplicate]为什么我在使用我的功能时得到 [本机代码] [重复]
【发布时间】:2018-07-09 14:39:12
【问题描述】:

我正在尝试创建一个反转字符串字母大小写的函数,因此字符串“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] }"

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

【问题讨论】:

  • 请查看“重复”链接。这不仅仅是同一个任务,你的错误也是相似的。
  • newChar = string.charAt(i).toLowerCase你忘了加上(),因此,你不是调用toLowerCase,而是用函数分配变量newCHar

标签: javascript native-code


【解决方案1】:

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"));

【讨论】:

    猜你喜欢
    • 2016-11-17
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多