簡體   English   中英

類型錯誤:無法讀取未定義 |CodeWars| 的屬性“toUpperCase”

[英]TypeError: Cannot read property 'toUpperCase' of undefined |CodeWars|

所以,這里是kata:

完成方法/函數,以便它將破折號/下划線分隔的單詞轉換為駝峰式大小寫。 僅當原始單詞大寫時,輸出中的第一個單詞才應大寫(稱為 Upper Camel Case,通常也稱為 Pascal 大小寫)。

示例 "the-stealth-warrior" 轉換為 "theStealthWarrior" "The_Stealth_Warrior" 轉換為 "TheStealthWarrior"

我想出了這個解決方案(在谷歌的幫助下):

function toCamelCase(str) {
  const arrChar = Array.from(str)[0];

  let result = '';
  if (arrChar !== arrChar.toUpperCase()) {
    result += str
      .toLowerCase()
      .replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
  } else if (arrChar === arrChar.toUpperCase()) {
    result += (' ' + str)
      .toLowerCase()
      .replace(/[^a-zA-Z0-9]+(.)/g, (m, ch) => ch.toUpperCase());
  }
  return result;
}

它在 Vs 代碼中完美運行,但 CodeWars 給了我這個:

TypeError: Cannot read property 'toUpperCase' of undefined
    at toCamelCase
    at it
    at begin
    at it
    at describe
    at /runner/frameworks/javascript/cw-2.js:152:11
    at Promise._execute
    at Promise._resolveFromExecutor
    at new Promise
    at describe
    at /home/codewarrior/index.js:23:5
    at /home/codewarrior/index.js:33:5
    at Object.handleError

任何想法為什么? 提前致謝..

在 codewars 中,他們提供的第一個測試用例是一個空字符串。 因此 array.from("")[0] 將產生 undefined 並在以后導致錯誤。 這可以通過檢查字符串是否為空並返回它來避免。 我建議始終尋找任務定義中描述的邊緣情況,並從它們開始你的邏輯。

嘗試這個。

const arrChar = Array.from(str)[0] ?? '';

給函數的參數可能是一個空字符串,這實際上可能導致此屬性“toUpperCase”未定義問題。 造成這種情況的主要原因包括:

  1. 在未初始化為字符串的類屬性上調用方法
  2. 在不存在的數組索引上調用方法

因此,請檢查 arrChar 值。

if(!Array.from(str)[0]){
    arrChar = "";
}

ch 是任何對象,可能不是字符串, ch.toUpperCase()中的 ch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM