Just getting my feet wet in Development. I already see frustration setting in but will not give up easily. I want to learn. Have a few projects that I am doing for a boot camp. Could use veteran eyes and see why it is coming up undefined? Challenge 2 needs the sum of array added to the mix . could use help on that also.
//challenge 1
var arr1 = [8,6,7,5,3,0,9];
for (var i = 0; i < arr1.lenght; i++) {
var arr1 = arr1[i];
console.log(arr1);
}
//challenge 2
var arr2 = [4,7,13,13,19,37,-2];
for (var i = 0; i < arr2.length; i++); {
var arr2 = arr2[i];
console.log(arr2[i]);
}
For the first one, you have a typo: lenght
should be length
. Also, you shouldn’t redeclare arr1
inside the loop; you should pick another name that doesn’t collide:
var arr1 = [8, 6, 7, 5, 3, 0, 9]
for(var i = 0; i < arr1.length; i++) {
var v = arr1[i]
console.log(v)
}
For the second challenge, you have the same redeclaration problem, and you also have an extra semicolon at the end of the for
loop initialization: ); {
should be ) {
.
Edit: Oh, you want the sum? You should add something to track that.
var arr2 = [4, 7, 13, 13, 19, 37, -2]
var s = 0
for (var i = 0; i < arr2.length; i++) {
s += arr2[i]
}
console.log(s)
1 Like
Wow , OK , Thank you. I am sure the syntax of programming will drive me nuts for a while.But normal typos I need to be more aware of.
So do I not need to declare arr1 in the loop because the program needs to know what array I am referring too?
Followed you tube instructions?Not sure.
As far as to define the sum of the array , it should be sum = aar2 , then console,log(sum)?
Yep, syntax will get you every time if you’re not careful to check it.
Usually you want to declare a variable exactly once, otherwise you risk aliasing. A variable declaration has something to do with its identity, so if you make multiple declarations, there will be multiple slots as your program runs with the same name, which often generates confusion.
You can declare new variables inside the indented body of a loop, but those variables aren’t meant to last outside of a loop iteration.
The second block of code I posted shows a way to calculate the sum of the contents of the array. You’ll probably need to use the +
or +=
operators somewhere, since they represent addition / summation.
Perfect , Thanks
I will try that . I am glad I found this community.
This will be very helpful moving forward.
1 Like