我写了下面的函数,但它们的输出略有不同。为什么在第一个例子中没有执行join()
?
function dice(number) {
let results = [];
for (let i = 1; i <= number; i++) {
results.push(Math.floor(Math.random() * (6 - 1)) + 1);
}
results.join(", ");
return `Rolled ${number} dice: ${results}`;
}
//example output: Rolled 3 dice: 5,2,1
但是当我这样做时...... join()
被执行:
function dice(number) {
let results = [];
for (let i = 1; i <= number; i++) {
results.push(Math.floor(Math.random() * (6 - 1)) + 1);
}
return `Rolled ${number} dice: ${results.join(", ")}`;
}
//example output: Rolled 3 dice: 5, 2, 1
有人可以向我解释为什么会这样吗?还有其他任何情况我需要注意代码执行方式的“顺序”吗?
答案 0 :(得分:3)
来自MDN:
join()方法将数组的所有元素(或类数组对象)连接成一个字符串并返回该字符串。
您必须将其分配给result
:
results = results.join(", ");
function dice(number) {
let results = [];
for (let i = 1; i <= number; i++) {
results.push(Math.floor(Math.random() * (6 - 1)) + 1);
}
results = results.join(", ");
return `Rolled ${number} dice: ${results}`;
}
var res = dice(5);
console.log(res)
&#13;