我想在某处显示名称+姓氏的用户名。 我有一个功能:
function getData(count) {
names = ["Michał", "Jan", "Katarzyna", "Andrzej", "Józef", "Bartek", "Mikołaj", "Tomasz", "Julian", "Brajan", "Dżesika"];////////////// bez var
var surnames = ["Noga", "Kowalski", "Nowak", "Pazura", "Duda", "Komorowski", "Tomczyk", "Józefowicz", "Lechicki", "Goldberg"];
var result = [];
for (var i = 0; i < count; i++) {
var randomNameIndex = Math.floor(Math.random() * names.length);
var randomSurnameIndex = Math.floor(Math.random() * surnames.length);
name = names[randomNameIndex];
var surname = surnames[randomSurnameIndex];
result.push({
name: name,
surname: surname
});
}
return result
}
然后我想显示一个结果,所以我有另一个功能:
function textDisplay() {
//var username = name;
//var username = names[1];
//var username = getData(3);
//$(username) = names[1];
$("#nameDisplay").html(username);
}
评论中没有一行符号可行。 如何正确显示这些数组元素?
答案 0 :(得分:1)
getData()
返回一个对象数组。你需要遍历它们以获得所有名称。
function textDisplay() {
var data = getData(3);
var html = "";
$.each(data, function(i, {name, surname}) {
html += `Name: ${name} ${surname}<br>`;
});
$("#nameDisplay").html(html);
}
function getData(count) {
names = ["Michał", "Jan", "Katarzyna", "Andrzej", "Józef", "Bartek", "Mikołaj", "Tomasz", "Julian", "Brajan", "Dżesika"]; ////////////// bez var
var surnames = ["Noga", "Kowalski", "Nowak", "Pazura", "Duda", "Komorowski", "Tomczyk", "Józefowicz", "Lechicki", "Goldberg"];
var result = [];
for (var i = 0; i < count; i++) {
var randomNameIndex = Math.floor(Math.random() * names.length);
var randomSurnameIndex = Math.floor(Math.random() * surnames.length);
name = names[randomNameIndex];
var surname = surnames[randomSurnameIndex];
result.push({
name: name,
surname: surname
});
}
return result
}
textDisplay();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nameDisplay"></div>
&#13;