简体   繁体   中英

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.

The intetended body of the loop for(var i = 0; i <= howM; i++) is not enclosed in braces {..} . As a result, only the statement var sum = 0; will be executed in the loop. Also, you probably meant to say 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. You can use brackets 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(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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM