我正在解决运动问题。在Visual Studio中解决了它(它工作),将解决方案复制到浏览器(Codewars challenge)并返回此错误:
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不是函数”)。 谢谢!
答案 0 :(得分:5)
如果您收到号码,可以使用.toString()
方法。
我正在使用这样的东西:
if (typeof string === 'number') {
string = num.toString();
}
首先,使用typeof
运算符检查它是否为数字。
然后使用.toString
方法将其更改为字符串。希望它有所帮助:)
答案 1 :(得分:2)
如果您对字符串以外的内容调用.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
&#13;