簡體   English   中英

TypeError:string.split不是函數

[英]TypeError: string.split is not a function

我正在解決運動問題。 在Visual Studio中解決了它(起作用),將解決方案復制到瀏覽器(Codewars挑戰),並返回以下錯誤:

TypeError: string.split is not a function
   at bulk
    at _
    at begin
    at it
        at /runner/frameworks/javascript/cw-2.js:159:11
    at Promise._execute
    at Promise._resolveFromExecutor
    at new Promise
    at Object.describe
            at Object.handleError
        at ContextifyScript.Script.runInThisContext
    at Object.exports.runInThisContext

這是我的代碼:

 function bulk(string) { var arr = string.split(", "); var whatYouAte = []; for (var i = 0; i < arr.length; i++) { arr[i] = arr[i].replace(/g /g, ' '); whatYouAte.push(arr[i].split(" ")); } var proteins = 0; var calories = 0; console.log(whatYouAte); for (var j = 0; j < whatYouAte.length; j++) { var foodAmount = whatYouAte[j][0]; var foodName = whatYouAte[j][1]; var foodProteinKcal = food[foodName][0]; var foodCarbKcal = food[foodName][1]; var foodFatKcal = food[foodName][2]; proteins += foodAmount / 100 * foodProteinKcal; calories += foodAmount / 100 * (foodProteinKcal + foodCarbKcal + foodFatKcal); } return "Total proteins: " + proteins + " grams, Total calories: " + calories + "."; } 

我想我曾經有一個類似的問題,可以通過制作this.split()解決,但現在不起作用(Codewars不接受,返回“ TypeError:this.split不是函數”)。 謝謝!

如果要獲取數字,則可以使用.toString()方法。

我正在使用這樣的東西:

if (typeof string === 'number') {
    string = num.toString();
}

首先,使用typeof運算符檢查它是否為數字。 然后使用.toString方法將其更改為字符串。 希望能幫助到你 :)

如果您在字符串以外的其他地方調用.split() ,則JS運行時將找不到該類型的.split()方法。 確保將字符串傳遞給函數。

這是一個例子:

 var result = "Scott Marcus".split(" "); console.log(result); // ["Scott", "Marcus"] var value = 42 value.split("4"); // ERROR: split is not a function 

暫無
暫無

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

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