27/33 Loop the Loop questions


#1


So i got a working solution and its a common one. Won't post it here, because we can't post solutions, afaik.
My question is, can you make it better?
1) The loop - can we do this without the for (i=0, i>x, i++), but with something simpler to understand, like for i in family, which i believe is used in python?
2) Can we create a non-empty array with variables and assign them later?
By the time the compiler gets to the for loop the array and those variables will already exist.
3) Anything else maybe?


// Our Person constructor
function Person(name, age) {
    this.name = name;
    this.age = age;
};

// Now we can make an array of people
var family = [var alice, bob, michelle, timmy];

var alice = new Person ("alice", 40);
var bob = new Person ("bob", 42);
var michelle = new Person ("michelle", 8);
var timmy = new Person ("timmy", 6);

// loop through our new array
for i in family {
    console.log(family[i].name);
};


#2

for starters, you could simply declare the array after the instances and store them in the array:

var alice = new Person ("alice", 40);
var bob = new Person ("bob", 42);
var michelle = new Person ("michelle", 8);
var timmy = new Person ("timmy", 6);

var family = [alice, bob, michelle, timmy]

actually, js has a foreach loop which you can use:

family.forEach(function(element) {
    console.log(element);
});

you can also extend it to manipulate the array:

family.forEach(function(element, index, array) {
    array[index] = "updae"
});

see mdn - foreach


#3

You can do this in JS, which I think you learn a bit further on. It's called a for...in loop.
It's formatted the same (i think) in that it's for (var prop in obj) {};

You will also learn this later on.
But if you can't wait, it's formatted like " array.push("what you want to add"); "


#4

@javascriptjo is right, for .. in loop allows to loop over object properties, but you can't use this for what you want to use it for. Python has relatively simply syntax.

uhm.. how did you want to do this javascriptjo?


#5

How did I want to do what?


#6

Can we create a non-empty array with variables and assign them later?


#7

You can add things to the array later, yes. You use the .push() method for that.
Isn't that what he asked?

If he asked if you could assign the variable later then that's more of a "depends" type of answer.

edit: I just realized I misread. I'm not all that sure what he's asking.


#8

this i know.

i don't so, i think what he asks is this:

var example_string

var example_list = [example_string];

example_string = "one";
example_list[0] = example_string

tough this seems "possible" it is not very nice.

no problem, that can happen, now you understand why i was confused :wink:


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.