var student = [{
"fname": "Jackie",
"mname": "Lee",
"lname": "Li"
}, {
"fname": "Ken",
"mname": "Ryu",
"lname": "Sha"
}];
for (var i = 0; i < student.length; i++) {
console.log(student[i].fname + " " + student[i].mname + ". " + student[i].lname ? student[i].fname + " " + student[i].mname + ". " + student[i].lname + " , " : " ");
}
我正在尝试将a td
中的名称组合起来,这些名称来自数组。我能够通过上面的代码组合名称。问题是在姓氏上还有一个,
只想在没有更多名字的情况下摆脱逗号。我被这个简单的逗号打了几个小时。任何想法都是适用的。
答案 0 :(得分:6)
一种简单的方法是构建一个数组,然后使用.join(", ")
:
var student = [{
"fname": "Jackie",
"mname": "Lee",
"lname": "Li"
}, {
"fname": "Ken",
"mname": "Ryu",
"lname": "Sha"
}];
var names = [];
for (var i = 0; i < student.length; i++) {
names.push(student[i].fname + " " + student[i].mname + ". " + student[i].lname);
}
snippet.log(names.join(", "));
&#13;
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
Array#map
:
var student = [{
"fname": "Jackie",
"mname": "Lee",
"lname": "Li"
}, {
"fname": "Ken",
"mname": "Ryu",
"lname": "Sha"
}];
snippet.log(student.map(function(entry) {
return entry.fname + " " + entry.mname + ". " + entry.lname;
}).join(", "));
&#13;
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
答案 1 :(得分:3)
如果我理解你的问题,那么应该这样做:
for(var i = 0 ; i < student.length; i++){
var name = student[i].fname + " " + student[i].mname + ". " + student[i].lname ? student[i].fname + " " + student[i].mname + ". " + student[i].lname: " ";
if (i < (student.length - 1)) {
name += ',';
}
}
答案 2 :(得分:3)
试试这段代码
var student = [{
"fname": "Jackie",
"mname": "Lee",
"lname": "Li"
}, {
"fname": "Ken",
"mname": "Ryu",
"lname": "Sha"
}]
for (var i = 0; i < student.length; i++) {
var out = student[i].fname + " " + student[i].mname + ". " + student[i].lname;
if (i < student.length - 1) {
out += ", ";
} else {
out += " ";
}
snippet.log(out);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
答案 3 :(得分:2)
试试这个jsfiddle
你应该这样使用:
var student = [{
"fname": "Jackie",
"mname": "Lee",
"lname": "Li"
}, {
"fname": "Ken",
"mname": "Ryu",
"lname": "Sha"
}]
for (var i = 0; i < student.length; i++) {
console.log(student[i].fname + " " + student[i].mname + ". " + student[i].lname + ((i < student.length - 1) ? ", " : " "));
}