简体   繁体   English

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

[英]Javascript Object variable references to strings on the console/page

Ok so i have this code. 好的,所以我有这段代码。

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

Basically i want the array contacts to be printed out to either the console, or the page. 基本上,我希望将阵列联系人打印到控制台或页面上。 However if i use 但是如果我使用

console.log(contacts)

it does not print out the array as [mary,joseph,guy], instead it gives me the object keys and values beside the position in the array. 它不会以[mary,joseph,guy]的形式打印出数组,而是为我提供了数组中位置旁边的对象键和值。

I just want to print out Objectmary,Objectjoseph,Objectguy to the console or on the page. 我只想将Objectmary,Objectjoseph,Objectguy打印到控制台或页面上。

Try using Array.prototype.forEach() to iterate objects, console.log() objects firstName property; 尝试使用Array.prototype.forEach()迭代对象, console.log()对象的firstName属性; use Array.prototype.map() to return array containing only firstName properties of objects 使用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); 

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM