我有这个数组:
items = []
items[0] = {id: "805", category: 'Apple'}
items[1] = {id: "804", category: 'Watermelon'}
items[2] = {id: "804", category: 'Plum'}
和forEach,当我得到category value
时。
var result = '';
items.forEach(function(item) {
result += item.category;
});
console.log(result);
但问题是在console.log中我得到了Apple, Watermelon, Plum
,这得到了我的结果。我如何在控制台中获得这样的输入 -
Apple
Watermelon
Plum
答案 0 :(得分:1)
如果您想添加换行符:
const items = [
{id: "805", category: 'Apple'},
{id: "804", category: 'Watermelon'},
{id: "804", category: 'Plum'}
];
let result = '';
items.forEach(function(item) {
if (result) result += '\n';
result += item.category;
});
console.log(result);
但是当迭代数组以在最后生成单个值时,使用.reduce
更合适:
const items = [
{id: "805", category: 'Apple'},
{id: "804", category: 'Watermelon'},
{id: "804", category: 'Plum'}
];
const result = items.reduce((resultSoFar, item) => {
if (resultSoFar) resultSoFar += '\n';
resultSoFar += item.category;
return resultSoFar;
}, '');
console.log(result);
答案 1 :(得分:1)
在末尾添加'\n'
items = []
items[0] = {id: "805", category: 'Apple'}
items[1] = {id: "804", category: 'Watermelon'}
items[2] = {id: "804", category: 'Plum'}
var result = '';
items.forEach(function(item) {
result += item.category+'\n'; //add '\n' at the end
});
result=result.substr(0,result.length-1); // remove last character(which is '\n')
console.log(result);
答案 2 :(得分:1)
你必须这样做:
buildTypes {
release {
debuggable false
minifyEnabled true
shrinkResources true
useProguard true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}

答案 3 :(得分:0)
items = []
items[0] = {id: "805", category: 'Apple'}
items[1] = {id: "804", category: 'Watermelon'}
items[2] = {id: "804", category: 'Plum'}
var result = '';
items.forEach(function(item)
{
result += item.category + '\r\n';
});
console.log(result);

答案 4 :(得分:-1)
在您的情况下,您将使用map
和join
的组合。 map
创建的数组只包含category
的值,而join
会将这些值加在一起。
items = [
{id: "805", category: 'Apple'},
{id: "804", category: 'Watermelon'},
{id: "804", category: 'Plum'}
]
var result = items.map(item => item.category).join('\n')
console.log(result)
答案 5 :(得分:-2)
items = []
items[0] = {id: "805", category: 'Apple'}
items[1] = {id: "804", category: 'Watermelon'}
items[2] = {id: "804", category: 'Plum'}
var result = '';
items.forEach(function(item) {
result += item.category;
});
console.log(result);
使用上面的代码。错误是dscr属性