简体   繁体   English

TypeError:string.split不是函数

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

I'm solving an exercise problem. 我正在解决运动问题。 Solved it in Visual Studio (it worked), copied the solution to the browser (Codewars challenge) and it returned this error: 在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

Here's my code: 这是我的代码:

 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 + "."; } 

I think I once had a similar problem and solved it by making this.split(), but now this doesn't work (Codewars doesn't accept, returns "TypeError: this.split is not a function"). 我想我曾经有一个类似的问题,可以通过制作this.split()解决,但现在不起作用(Codewars不接受,返回“ TypeError:this.split不是函数”)。 Thanks! 谢谢!

If you are getting a number you can use the .toString() method. 如果要获取数字,则可以使用.toString()方法。

I'm using something like this: 我正在使用这样的东西:

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

First, use the typeof operator to check if it's a number. 首先,使用typeof运算符检查它是否为数字。 Then use the .toString method to change it to a string. 然后使用.toString方法将其更改为字符串。 Hope it helps :) 希望能帮助到你 :)

If you call .split() on something other than a string, the JS runtime won't find the .split() method for that type. 如果您在字符串以外的其他地方调用.split() ,则JS运行时将找不到该类型的.split()方法。 Make sure you are passing a string to your function. 确保将字符串传递给函数。

Here's an example: 这是一个例子:

 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