[英]Can someone please tell me why this code wont run?
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for(var i = 0; i <= howM; i++)
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1)); }
console.log(sum);
It tells me this "TypeError: Cannot read property 'replace' of undefined at eval:13:11" which makes no sense to me because its right above it. 它告诉我这个“ TypeError:无法读取eval:13:11处未定义的属性'replace'”,这对我来说毫无意义,因为它位于其上方。
The intetended body of the loop for(var i = 0; i <= howM; i++)
is not enclosed in braces {..}
. for(var i = 0; i <= howM; i++)
的循环的主体未包含在括号{..}
。 As a result, only the statement var sum = 0;
结果,只有语句
var sum = 0;
will be executed in the loop. 将在循环中执行。 Also, you probably meant to say
i < howM
. 另外,您可能想说
i < howM
。 So you want something like this for the loop: 因此,您需要这样的循环:
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
Check the comments: 检查评论:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < parseInt(howM); i++)
arr.push(prompt("Enter a card:")); //No curly braces is fine when its a single line. When there's no braces, JS just runs the next line x amount of times
console.log(arr)
var sum = 0; //Create sum out here. Setting it to zero every loop defeats the purpose
for(var i = 0; i < arr.length; i++)//You said "i <= howM". Better to use the length of the array that is being looped through
{ //Use curly braces to show what code to execute repeatedly
var eXt = arr[i]; //Set eXt to the current number
eXt = eXt.replace("-", ""); //No need for regex
sum += parseInt(eXt); //Convert the input to a number, then add it to sum
}
console.log(sum);
The second for
loop doesn't have brackets around it. 第二个
for
循环没有括号。 You can MUST use brackets
UNLESS it is a one line loop.
除非是单行循环,否则
必须使用方括号。 For example:
例如:
This is fine: 这可以:
for (var i=0;i<100;i++)
console.log(i);
This is NOT: 这不是:
for (var i=0;i<100;i++)
var x = i;
x++;
console.log(x);
So the second for loop should be this: 因此,第二个for循环应为:
for(var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
console.log(sum);
}
Also in the first for
loop I would use arr[i] = value
instead. 同样在第一个
for
循环中,我将改用arr[i] = value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.