我想编写一个函数,该函数将数组作为参数,并返回一个字符串,其中数组中的项目具有前面的数字。例如。下面的line
数组有三个成员Ava
,Adam
,John
。我希望函数返回以下字符串:
The line is currently: 1. Ava, 2. Adam, 3. John
line = ['Ava', 'Adam', 'John']
function currentLine(line) {
if (line.length === 0) {
return "The line is currently empty.";
}
return "The line is currently: "
}
答案 0 :(得分:2)
将此作为你的最后一句话:
var result = line.map(function (value, index) {
return (index + 1) + '. ' + value;
}).join(', ');
return "The line is currently: " + result;
答案 1 :(得分:0)
您可以通过以下方式完成此操作......
let line = ['Ava', 'Adam', 'John'];
function currentLine(line) {
if (line.length !== 0) {
let result = "The line is currently: ";
line.forEach((e, i) => {
result += (i + 1) + '. ' + e + ', ';
});
return result.slice(0,-2);
} else return "The line is currently empty.";
}
console.log(currentLine(line));
答案 2 :(得分:0)
var line = ['Ava', 'Adam', 'John']
function currentLine(line) {
if (line.length === 0) {
return "The line is currently empty.";
}
var newLine = line.map(function (item ,index){
return (index+1) + ". " + item;
});
return "The line is currently: " + newLine.join(", ");
}
console.log(currentLine(line));
答案 3 :(得分:0)
纳兹-Al系,
此代码将允许您实现所需的结果。另外,您可以将其他数组传递给函数并实现相同的输出。
var line = ['Ava', 'Adam', 'John'];
function currentLine(array) {
var output = "";
if (array.length === 0) {
return "The line is currently empty.";
}
else {
for(var i = 0; i < array.length; i++){
output += (Number([i]) + 1) + ". " + array[i];
if(i !== array.length - 1) {
output = output + ", ";
}
}
}
return "The line is currently: " + output;
}
&#13;