[英]JS : console.log displays "undefined" in the end of an array of objects
I wanted to display a simple array's items on the console, using foreach.我想使用 foreach 在控制台上显示一个简单的数组项。 It dispalys all the items(it's OK), but it displays "cars : undefined" at the end.
它显示所有项目(没关系),但最后显示“汽车:未定义”。 I dont want to display "cars : undefined", but only the 3 items of the array.
我不想显示“汽车:未定义”,而只想显示数组的 3 项。 How to do ?
怎么做 ?
var cars = [{ year: 2011, type: "Volvo" }, { year: 1999, type: "Volvo" }, { year: 2003, type: "Volvo" }]; console.log("1"); console.log("cars : " + cars.forEach(a => console.log(a))); console.log("2");
forEach()
returns undefined
. forEach()
返回undefined
。 try like this试试这样
var cars = [{
year: 2011,
type: "Volvo"
}, {
year: 1999,
type: "Volvo"
}, {
year: 2003,
type: "Volvo"
}];
console.log("1");
console.log("cars : ");
cars.forEach(a => console.log(a))
console.log("2");
console.log outputs a string, but returns undefined. console.log 输出一个字符串,但返回未定义。 So, the inner one writes your data, returns undefined, and the outer one writes 'cars: undefined'
所以,内层写你的数据,返回未定义,外层写“汽车:未定义”
=> You should produce a string inside the log function, like this : => 您应该在 log 函数中生成一个字符串,如下所示:
console.log("cars :" + cars.map(a => ` ${a.type} ${a.year}` ));
That will log:这将记录:
cars : Volvo 2011, Volvo 1999, Volvo 2003
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.