Javascript将数组中对象的属性转换为字符串
问题描述:
我有一个对象数组,它们都是同一类的所有实例,如下所示:
I have an array of objects which are all instances of the same class like below:
class Foo {
constructor(bar){
this.bar = bar;
}
}
var myArr = [new Foo("1"), new Foo("2"), new Foo("3"), new Foo("4")];
我希望能够将数组中每个对象的bar属性加入逗号分隔的字符串中。
I want to be able to join the bar property of each object in the array into a comma separated string.
是否可以在对象的属性上调用.join方法?如果不是低于最有效的方法呢?
Is it possible to call the .join method on the property of an object? If not is below the most efficent way to do this?
var result = "";
for (var i = 0; i < myArr.length; i++){
result += myArr[i].bar+","
}
还是还有其他方法?
答
您可以使用 Array.prototype.map
:
You can use Array.prototype.map
:
var result = myArr.map(function(x) { return x.bar; }).join(',');