gpt4 book ai didi

javascript - 结合数据/变量 jquery

转载 作者:行者123 更新时间:2023-11-28 03:58:28 24 4
gpt4 key购买 nike

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 + " , " : " ");
}

我正在尝试在 td 中组合名称,这些名称来自数组。我能够通过上面的代码组合名称。问题是在姓氏上还有一个 , 只是想在后面没有更多名字时去掉逗号。我被这个简单的逗号困扰了几个小时。任何想法都是值得赞赏的。

FIDDLE

最佳答案

一种简单的方法是建立一个数组,然后使用 .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(", "));
<!-- 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>

使用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(", "));
<!-- 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>

关于javascript - 结合数据/变量 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30779041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com