-2

How to get name, age, salary from the array products. And can you explain me what is wrong?

var products = [
 {name: 'Коля', age: 30, salary: 400},
 {name: 'Вася', age: 31, salary: 500},
 {name: 'Петя', age: 32, salary: 600},
];

var btn = document.getElementById("myBtn");
btn.addEventListener("click", funct);


function funct(){
  for( var i = 0; i < products.length; i++ ){
    document.write( " this " + products[i] );
  }
  return;
}
console.log(funct());
<button id="myBtn">Start</button>
Mamun
  • 66,969
  • 9
  • 47
  • 59
Marie
  • 153
  • 2
  • 10
  • 5
    Access it's properties i.e. `products[i].name` – Satpal May 01 '18 at 10:40
  • 2
    because you're trying to print the whole object, not the individual properties from it. And JS doesn't know how to do that, because it's an object and not a string or number. Refer to the properties by name e.g. `products[i].name`, or if you don't know in advance what they'll be, loop through them with an inner `foreach` loop – ADyson May 01 '18 at 10:40
  • Satpal and Adyson thank you) i got it – Marie May 01 '18 at 10:47

1 Answers1

3

You have to specify property name like products[i].name not the whole object:

var products = [
 {name: 'Коля', age: 30, salary: 400},
 {name: 'Вася', age: 31, salary: 500},
 {name: 'Петя', age: 32, salary: 600},
];

var btn = document.getElementById("myBtn");
btn.addEventListener("click", funct);


function funct(){
  for( var i = 0; i < products.length; i++ ){
    console.log( "name: " + products[i].name );
    console.log( "age: " + products[i].age );
    console.log( "salary: " + products[i].salary );
  }
 
}
<button type="button" id="myBtn">Start</button>
Mamun
  • 66,969
  • 9
  • 47
  • 59