Can someone please tell me why this code wont run? - javascript

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 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(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.

Related

I want to print a square using the hash characters, javascript

I am trying to print a square using the hash character
function square(num){
for(i = 0; i < num; i++){
for(j = 0; j < num; j++){
console.log("#");
}
console.log(" ");
}
}square(2);
/* my output is:
"#"
"#"
"#"
"#"
instead of:
"##"
"##"
*/
Every time you console.log(), the console will print a new line. You need to add each row to one line like this:
function square(num){
for(i = 0; i < num; i++){
let row = ''
for(j = 0; j < num; j++){
row+='#'
}
console.log(row+" ");
}
}
square(4);
Creating a function named square to return a square pattern.Using squareArray as the solution array and result string to store the value for each inner loop.Finally, using join to convert array to string.
function square(num) {
const squareArray = [];
let result;
for (let i = 0; i < num; i++) {
result = "";
for (let j = 0; j < num; j++) {
result += "#";
}
squareArray.push(result);
}
return squareArray.join("\n");
}
console.log(square(2));
console.log(square(4));
console.log(square(6));

Adding different number of '-' in every loop (javascript)

I need to create a string like this: 01-2--3---4----5-----6------7------- for a let n=7, using a loop.
I've created something like this so far:
let numbers = '';
n = 7;
for(i=0; i<=n; i++) {
numbers += i;
if (i>0) {
numbers += ('-')
}}
which gives me: "01-2-3-4-5-6-7-". Don't know how to change the code so that it could multiply the number of '-' equal n in every loop.
What you need is a nested loop, to iterate over the value of i in the outer loop.
const n = 7
let result=''
for (let i = 0; i <= n; i++) {
let dashes=''
for(let j=0; j < i; j++){
dashes+='-'
}
result+= `${i}${dashes}`
}
console.log(result)
You could use String#repeat for the wanted dash.
Do not forget to declare any variable.
let numbers = '',
n = 7;
for (let i = 0; i <= n; i++) numbers += i + '-'.repeat(i);
console.log(numbers);
This the solution for your problem:
var numbers = '';
var n = 7;
for(var i = 0; i <= n; i++) {
numbers += i;
for(var j = 0; j < i; j++) {
numbers += "-";
}
}

For loop through array.length only executes once

The code below only executes through the first for loop once, yet all the other for loops perform as expected. Does anyone know why this is the case? I'm not sure how relevant the bulk of the (inefficient, poorly formatted) code within the loop is but I include it nonetheless.
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
for (i = 0; i < numbers.length; i++) {
var current = numbers[i];
var currentStr = current.toString();
var reverseStr = currentStr.split('').reverse().join('');
var reverseArr = [];
for (i = 0; i < reverseStr.length; i++) {
reverseArr.push(reverseStr[i]);
}
var A = 0;
for (i = 0; i < reverseArr.length; i += 2) {
A += Math.round((reverseArr[i]));
}
var evenDigits = [];
for (i = 1; i < reverseArr.length; i += 2) {
evenDigits.push(reverseArr[i]);
}
for (i = 0; i < evenDigits.length; i++) {
evenDigits[i] = evenDigits[i] * 2;
if (evenDigits[i] > 9) {
var temp = evenDigits[i].toString();
var firstInt = Math.round(temp[0]);
var secondInt = Math.round(temp[1]);
evenDigits[i] = firstInt + secondInt;
}
}
var B = 0;
for (i = 0; i < evenDigits.length; i++) {
B += evenDigits[i];
}
var sum = A + B;
if (sum % 10 == 0) {
console.log('Yes');
} else console.log('No');
}
In your code you are using same instance of 'i' variable to iterate all loops.
Solution is to use different index variables to iterate external and internal loops
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
var i = 0;
var j = 0;
for (j=0; j < numbers.length; j++) {
var current = numbers[j];
/...
}
JavaScript behaves like this because 'i' is not scoped to block (like in Java od C#). In ES2015 you can use let or const to bind variable to block scope (in this sample to for loop)

How to I run a function for each piece of an array within a for loop in Javascript?

I have this so far, trying to get it to find the sum of each one of any number of inputted numbers with integers and "-"s.
When I run this,
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
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));
}
sumpre.push(sum);
}
console.log(sumpre)
I have also tried
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);
In both cases I get the sum for the first piece in the array and then undefined. How do I get it to run for each piece? I kind of have an idea of what is wrong with it I just don't quite know how to fix it.
You need to use a second counter for the nested for loop, like so:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace (/-/g, "");
for (var j = 0; j < eXt.length; j++) {
sum += parseInt(eXt.substr(j, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
Your var sum = 0; inside your for-loop meaning sum variable will not be accessible outside of the loop

"string.match()" is not a function?

I wrote a function to count the length and vowels in a word and output them in objects in an array. Yet I get the error "word.match() is not a function" where word is a string.
function wordData(string){
var stringSplit = string.split(' ');
var output = [];
for(var i = 0; i <= stringSplit.length; i++){
var eachWord = stringSplit[i];
var vowel = eachWord.match(/[aeiou]/gi);
var vowelCount = vowel ? vowel.length : 0;
var objectData = {};
objectData.word = eachWord;
objectData.length = eachWord.length;
objectData.vowels = vowelCount;
output.push(objectData);
}
return output;
}
console.log(wordData('some really awesome string'));
any idea what is wrong?
for(var i = 0; i <= stringSplit.length; i++)
That'll go up past the last index of your array of strings. Therefore, it will be undefined, and you can't call match on undefined.
Do this instead:
for(var i = 0; i < stringSplit.length; i++)
Index out of bounds
for(var i = 0; i <= stringSplit.length; i++){
should be
for(var i = 0; i < stringSplit.length; i++){

Categories

Resources