Javascript对象变量引用控制台/页面上的字符串

时间:2016-01-21 23:00:10

标签: javascript arrays object logging console

好的,我有这个代码。

var Objectmary={firstName:"mary",lastName:"marshall"};
var Objectjoseph={firstName:"joseph",lastName:"marshall"};
var Objectguy={firstName:"guy", lastName:"steele"};
var contacts=[Objectmary,Objectjoseph,Objectguy];

基本上我希望将数组联系人打印到控制台或页面。但是,如果我使用

console.log(contacts)

它不会将数组打印为[mary,joseph,guy],而是在数组中的位置旁边给出了对象键和值。

我只想将Objectmary,Objectjoseph,Objectguy打印到控制台或页面上。

2 个答案:

答案 0 :(得分:0)

尝试使用Array.prototype.forEach()来迭代对象,console.log()对象firstName属性;使用Array.prototype.map()返回仅包含对象firstName属性的数组

var Objectmary = {
  firstName: "mary",
  lastName: "marshall"
};
var Objectjoseph = {
  firstName: "joseph",
  lastName: "marshall"
};
var Objectguy = {
  firstName: "guy",
  lastName: "steele"
};
var contacts = [Objectmary, Objectjoseph, Objectguy];

contacts.forEach(function(obj) {
  console.log(obj.firstName, obj.lastName);
  document.body.innerHTML += obj.firstName + " " + obj.lastName + "<br>"
});

var names = contacts.map(function(obj) {
  return obj.firstName
});

console.log(names);

答案 1 :(得分:0)

var Objectmary   = { firstName: 'mary', lastName: 'marshall' },
    Objectjoseph = { firstName: 'joseph', lastName: 'marshall' },
    Objectguy    = { firstName: 'guy', lastName: 'steele' },
    contacts     = [Objectmary, Objectjoseph, Objectguy],
    array_string = '[';

for (var i = 0, l = contacts.length; i < l; i++) {
    array_string += contacts[i].firstName;
    if (i < (l - 1)) array_string += ', '; 
}
array_string += ']';
console.log(array_string);