JS 一直报告 "toString" 方法未定义

JS keep reporting "toString" method is undefined

我的目标是按字母顺序排列 givin 字符串。例如,给定字符串“The Holy Bible”,应该得到“BbeehHilloTy”。下面是代码:

function alphabetized(s) {
  let sArray = s.split(" ").join("").split("");
  //below to perform a bubble sorting
  for (let i = 0; i < sArray.length; i++) {
    for (let j = 0; j < sArray.length - i; j++) {
      if ((sArray[j].toString().toLowerCase()) > (sArray[j + 1].toString().toLowerCase())) {
        let tempItem = sArray[j];
        sArray[j] = sArray[j + 1];
        sArray[j + 1] = tempItem;
      }
    }
  }
  return sArray.join("");
}

console.log(alphabetized('The Holy Bible'));

我一直从 JS 控制台收到错误:

if ((sArray[j].toString().toLowerCase()) > (sArray[j + 1].toString().toLowerCase())) {
TypeError: Cannot read property 'toString' of undefined

如有任何帮助,我们将不胜感激!

问题不在于 toString 未定义。这是因为您正试图在 未定义的东西上调用 toString()

由于您在计算数组的结果时调用 toString(),您引用的数组元素似乎无效。您在两个地方执行此操作:sArray[j]sArray[j+1 ]。由于您正在从 0 到数组的长度遍历 j,因此您可以计算一个超过数组长度的值。

作为调试的一部分,尝试记录 j 的值以及您认为您正在评估的角色应该是什么。

问题来了。 未定义变量,无法调用 toString 方法。 所以你只需要添加这段代码。如果你什么都不想做

if(!sArray[j + 1]) continue;

这是一个小提示。调试是编码的好工具。试试吧!