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:
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"). Thanks!
If you are getting a number you can use the .toString()
method.
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. Then use the .toString
method to change it to a string. 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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.