use*_*695 27 javascript underscore.js
我想使用该reduce函数而不是这样做:
var result = '';
authors.forEach(
function(author) {
result += author.name + ', ';
}
);
console.log(result);
Run Code Online (Sandbox Code Playgroud)
所以在数组中authors有几个名字.现在我想用这个名字构建一个字符串,用逗号分隔(除了最后一个).
var result = authors.reduce(function (author, index) {
return author + ' ';
}, '');
console.log(result);
Run Code Online (Sandbox Code Playgroud)
abi*_*ful 51
一连串的答案刚刚进来,这里还有一个!
第一个选项是使用本机js连接方法,这消除了对reduce的需要.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
var authors = ['some author', 'another author', 'last author'];
var authorString = authors.join(",");
console.log(authorString);
Run Code Online (Sandbox Code Playgroud)
重要信息 - 如果您的数组包含对象,那么您可能希望在加入之前映射它:
var authors = [{name: 'some author'},{name: 'another author'},{name: 'last author'}]
var authorString = authors.map(function(author){
return author.name;
}).join(",");
console.log(authorString);
Run Code Online (Sandbox Code Playgroud)
或者,如果您真的对使用reduce有兴趣,请确保在传入回调时使用先前的值,当前值和索引.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
var authorString = authors.reduce(function(prevVal,currVal,idx){
return idx == 0 ? currVal : prevVal + ', ' + currVal;
}, '')
console.log(authorString);
Run Code Online (Sandbox Code Playgroud)
重要 - 再次,如果您的数组包含对象,那么您将需要确保使用'name属性':
var authors = [{name: 'some author'},{name: 'another author'},{name: 'last author'}];
var authorString = authors.reduce(function(prevVal,currVal,idx){
return idx == 0 ? currVal.name : prevVal + ', ' + currVal.name;
}, '')
console.log(authorString);
Run Code Online (Sandbox Code Playgroud)
Shi*_*lly 15
是的,所以这是一个对象.让我们首先映射名称:
var result = authors.map(function( author ) {
return author.name;
}).join(', ');
Run Code Online (Sandbox Code Playgroud)
小智 7
我也遇到过这个。这些答案中的大多数都没有考虑到您想要作者的名字,这意味着您有一个对象数组。
一行解决方案:
authors.reduce((prev, curr) => [...prev, curr.name], []).join(', ');
Run Code Online (Sandbox Code Playgroud)
你正在重新发明 join()
var authors = ["a","b","c"];
var str = authors.join(", ");
console.log(str);Run Code Online (Sandbox Code Playgroud)
如果你想使用 reduce 添加一个 if 检查
var authors = ["a","b","c"];
var result = authors.reduce(function (author, val, index) {
var comma = author.length ? ", " : "";
return author + comma + val;
}, '');
console.log(result);Run Code Online (Sandbox Code Playgroud)
由于我错过了让人们开心的映射部分......
var authors = [{
name: "a"
}, {
name: "b"
}, {
name: "c"
}];
var res = authors.map( function(val) { return val.name; }).join(", ");
console.log(res);Run Code Online (Sandbox Code Playgroud)
或者
var authors = [{
name: "a"
}, {
name: "b"
}, {
name: "c"
}];
var result = authors.reduce(function(author, val, index) {
var comma = author.length ? ", " : "";
return author + comma + val.name;
}, '');
console.log(result);Run Code Online (Sandbox Code Playgroud)