If (i == (int)i) use


#1

I'm trying to get a better grip on the loops learned in this topic. I'm rather new to programming, so I'm still trying to figure out how it all works.

I'm putting in the code I'm playing around with and got a few questions:

  1. Is this a correct way to make the program find out if the items in my list is an integer? And is my total variable working like I intend it to? (Adding the integer in my list and return the sum).

  2. My code returns this message: SyntaxError: Unexpected identifier. Am I just not finding a faulty parenthese or bracket? Or is this error due to a faulty code?

Code:
var myHobbies = ["Gaming", 42, 35, "Chess", "Programming", "Reading"];

for (var i = 0; i < myHobbies.length; i++) {
if (i ==(int)i) {
var total = 0;
total = total + i;
return total;
console.log(total);
} else {
console.log("My hobbies are " + i);
}
}


#2

Nope, this code is not correct. few problems:

if (i ==(int)i)

what are you trying to do here, and why? maybe you want to read this
You can't use returns in for loops:

return total;

well, you can, if the for loop is in a function. Only functions can return something.

what do you think this line will print:

console.log(total);

i think it will print 5, is that what you want?


#3

With that first one I'm trying to do what I asked in question 1, make the program find out if the items in my list are integers (not strings) and add them together in a variable called total. Then I want to add them together and return the new total, then print the number that would now be stored in the total variable.

I tried changing

into:
if (i === parseInt) {
}

The code now runs, but I'm pretty far away from what I had in mind.
I want the code to both run the total variable and print the total number of the added integers in my list, and print "My hobbies are ....".

Maybe I'm just too far off yet ^^


#4

Now i understand, you want to check if the item in the array is a number, if it is, add to total, give me a moment to think about this, since this outside the exercise

Now i have a dilemma, given this a beautiful thing where you could learn so much from, so i don't want to just give you the code, but rather help you in steps, is it alright if we move this to a chat?


#5

I apologise for my poor explanation in my first post, but yes, this is what I'm looking for.

That would be excellent, nothing would be better than that :smile:


#6

I will help you, as we speak i am writing a message. Give me some time, we will get there