开发者问题收集

无法读取未定义错误的属性“toLowerCase”仅在 Node 环境中发生

2017-06-01
5257

当我尝试在浏览器 JavaScript 控制台中运行以下代码时,它运行正常,但每次我尝试在 eligible.io 上运行它时,它都会返回以下错误。它使用 Node v6.6.0。

function isIsogram(word) {

  var entered = word;
  if (typeof (entered) === undefined) {
    return false
  }

  var passed = true;

  wordest = entered.toLowerCase();

  var counts = {};

  for (var i = 0; i <= wordest.length; i++) {
    var letter = wordest.toString().charAt(i)

    if (counts[letter]) {
      counts[letter] += 1
    }
    else {
      counts[letter] = 1
    }

    if (counts[letter] > 1) {
      return passed = false
    }
  }

  return passed
};

isIsogram("Altruistic");

错误消息:

/home/codewarrior/mocha:16
 for (i = 0; i <= wordest.length; i++) {
                          ^

TypeError: Cannot read property 'length' of undefined
    at isIsogram (/home/codewarrior/mocha:16:27)
    at Suite.describe (/home/codewarrior/mocha:42:23)
    at Object.create (/.npm-global/lib/node_modules/mocha/lib/interfaces/common.js:114:19)
    at context.describe.context.context (/.npm-global/lib/node_modules/mocha/lib/interfaces/bdd.js:44:27)
    at Suite.describe (/home/codewarrior/mocha:41:5)
    at Object.create (/.npm-global/lib/node_modules/mocha/lib/interfaces/common.js:114:19)
    at context.describe.context.context (/.npm-global/lib/node_modules/mocha/lib/interfaces/bdd.js:44:27)
    at /home/codewarrior/mocha:40:1
    at Object.<anonymous> (/home/codewarrior/mocha:64:11)
    at 
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at /.npm-global/lib/node_modules/mocha/lib/mocha.js:222:27
    at Array.forEach (native)
    at Mocha.loadFiles (/.npm-global/lib/node_modules/mocha/lib/mocha.js:219:14)
    at Mocha.run (/.npm-global/lib/node_modules/mocha/lib/mocha.js:487:10)
    at Object.<anonymous> (/.npm-global/lib/node_modules/mocha/bin/_mocha:459:18)
    at 
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
2个回答

使用

escape(entered).toLowerCase()

而不是直接使用代码。

D-Beloved
2017-06-25

在将 word 的值赋给 entered 之前,您应该检查它的值。

尝试将 if (word === undefined) { return false } 作为第一行,然后让我知道发生了什么!

DrunkDevKek
2017-06-01