我想这样做,以便数组中的每个项目都显示在单独的行中,但是我的“ \ n”不起作用。我放在错误的地方了吗?我尝试将其放在其他位置,但似乎没有什么不同。我的功能目标是遍历数组。
var employees = [];
employees[0] = "Zak";
employees[1] = "Jessica";
employees[2] = "Mark";
employees[3] = "Fred";
employees[4] = "Sally";
var showEmployee = function (names) {
'use strict';
showEmployee = employees;
return names;
};
showEmployee(employees);
window.console.log(showEmployee + "\n");
答案 0 :(得分:4)
您要在数组末尾添加换行符,您需要将其添加到数组中的每个元素之间(使用join)
var employees = [];
employees[0] = "Zak";
employees[1] = "Jessica";
employees[2] = "Mark";
employees[3] = "Fred";
employees[4] = "Sally";
var showEmployee = function (names) {
'use strict';
showEmployee = employees;
return names;
};
showEmployee(employees);
window.console.log(showEmployee.join("\n"));
答案 1 :(得分:0)
尝试是否有帮助
var employees = [];
employees[0] = "Zak";
employees[1] = "Jessica";
employees[2] = "Mark";
employees[3] = "Fred";
employees[4] = "Sally";
var showEmployee = function (names) {
names.map((name) => window.console.log(name));
};
showEmployee(employees);
答案 2 :(得分:0)
尝试遍历整个数组并改为记录每个员工:
employees.forEach(function(employee) {
console.log(employee)
})
答案 3 :(得分:0)
您只在输出的最后添加了\n
,而您似乎希望在数组中的每个元素之后打印\n
。您可以使用join
方法来获得所需的结果:
var employees = [];
employees[0] = "Zak";
employees[1] = "Jessica";
employees[2] = "Mark";
employees[3] = "Fred";
employees[4] = "Sally";
function showEmployee(a) {
return a.join(',\n')
}
console.log(showEmployee(employees));