0

How come when i try to add something into the "Enfant" array that i have initialized it gives me a number. In this case it gives me 3 when i add a string into it.

    var person=[];

function addPerson(n,a){
    person.push({ "Name" : n, "Age" : a, "Kid" : []});

}

addPerson("Julie",100); addPerson("Sarah",83);

function addKid(parentName,kidName){

    for(var i=0;i<person.length;i++){
        if (parentName== person[i].Name){
            person[i].Kid=person.push(kidName);
    }   
  }
}

addKid("Julie","Sarah");
print(person[0].Kid); //<--- gives me 3

2 Answers 2

1

Array.push returns the number of elements in the array after the push, which is what you're assigning to person[i].Kid

Sign up to request clarification or add additional context in comments.

Comments

0

You should do person[i].Kid.push instead.

function addKid(parentName,kidName){

    for(var i=0;i<person.length;i++){
        if (parentName== person[i].Name){
            person[i].Kid.push(kidName);
    }   
  }
}

2 Comments

thx. lets say i want to call the age of the parent of the kid. person[0].Kid[0].Age gives a blank. i have to re-push in the age?
@user3268216 yes, or you can change the line to person[1].Kid.push({ "Name" : kidName, "Age" : kidAge, "Kid" : []}); and add kidAge to the function definition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.