練習三:好多星星 加強版
Ponchimeow opened this issue · comments
Ponchimeow commented
請寫出一個函式 stars2,接收一個參數 n,並依照規律印出圖形。
stars2(1) 預期輸出:
*
stars2(3) 預期輸出:
*
**
***
**
*
stars2(5) 預期輸出:
*
**
***
****
*****
****
***
**
*
// ES6
const star = '*';
function stars2(n) {
for (let i = 0; i < n; i += 1) {
console.log(i > 0 ? star.repeat(i + 1) : star)
}
for (let i = n; i > 0; i -= 1) {
console.log(i > 0 ? star.repeat(i - 1) : star)
}
}
// 非 ES6
function stars2(n) {
if (n === 1) {
console.log(star)
}
for (let i = 1; i <= n; i += 1) {
console.log(new Array(i + 1).join(star))
}
for (let i = (n - 1); i > 0; i -= 1) {
console.log(new Array(i + 1).join(star))
}
}
// join
let str = '';
function join(n) {
for (let i = 0; i < n; i += 1) {
str += star;
}
return str;
}