【问题标题】:String.charAt() returning undefined in a loopString.charAt() 在循环中返回未定义
【发布时间】:2019-10-05 17:20:46
【问题描述】:

一定是我在这里遗漏了一些重要的东西。出于某种原因,.charAt(i) 在这段代码中返回 undefined。

Demo

    let images = {};
    let alphabet = 'abcdefghijklmnopqrstuvwxyz';
    let imageArray = ['a', 'b', 'c', 'd'];
    for (let i = 0; i < imageArray.length; i++){
        let letter = alphabet.charAt[i]; // returns undefined
        images[letter] = imageArray[i];
    }

    console.log(images); // {undefined: "d"}

【问题讨论】:

    标签: javascript arrays string charat


    【解决方案1】:

    你需要String#charAt的函数调用

    alphabet.charAt(i);
    //             ^ ^
    

    而不是带括号的property accessor

    let images = {};
    let alphabet = 'abcdefghijklmnopqrstuvwxyz';
    let imageArray = ['a', 'b', 'c', 'd'];
    for (let i = 0; i < imageArray.length; i++) {
      let letter = alphabet.charAt(i); // returns undefined
      images[letter] = imageArray[i];
    }
    
    console.log(images); // {undefined: "d"}

    【讨论】:

      【解决方案2】:

      您的语法有错误!当然,您想调用alphabet.charAt 函数。但是您正在使用charAt[i] 而不是charAt(i)。方括号是通过变量 (i) 访问数组/对象属性的语法,因此您最终会得到一个 函数的属性 charAt - 例如charAt[0]。但这不存在,所以它只是评估为undefined

      因此,要解决此问题,只需将方括号 (charAt[i]) 替换为圆括号 (charAt(i))。您总是使用括号来调用函数,而不是方括号。

      【讨论】:

        【解决方案3】:

        您必须将.charAt() 函数作为.charAt(i) 之类的函数调用,而不是.charAt[i]

        【讨论】:

          【解决方案4】:

          就是这样!,alphabet.charAt() 是函数,而不是数组。将 [] 更改为 () 并开始工作。

          let images = {};
          let alphabet = 'abcdefghijklmnopqrstuvwxyz';
          let imageArray = ['a', 'b', 'c', 'd'];
          for (let i = 0; i < imageArray.length; i++){
              let letter = alphabet.charAt(i); // returns undefined
              images[letter] = imageArray[i];
          }
          
          console.log(images); // {undefined: "d"}
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-11-29
            • 2016-06-19
            • 2013-02-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多