如何在javascript中从数组中获取信息

时间:2018-05-01 10:39:08

标签: javascript arrays

如何从数组name获取agesalaryproducts。 你能解释一下我的错误吗?



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());
&#13;
<button id="myBtn">Start</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

您必须指定属性名称,如products[i].name,而不是整个对象:

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>