我尝试使用map将字符串字符串元素添加到数组中,但是代码不起作用。那里有什么问题?
function towerBuilder(nFloors) {
let towerArray = [];
towerArray.length = nFloors;
let arrItem = '*' + ' ';
let newArr = towerArray.map(function(item, i) {
let n = 2 * i + 1;
item = arrItem.repeat(n);
return item;
});
}
答案 0 :(得分:2)
Array.map
会跳过undefined
个值。所以你必须使用new Array(length).fill(dummyValues)
function towerBuilder(nFloors) {
let towerArray = new Array(nFloors).fill("")
let arrItem = '*' + ' ';
let newArr = towerArray.map(function(item, i) {
let n = 2 * i + 1;
item = arrItem.repeat(n);
return item;
});
console.log(newArr)
}
towerBuilder(3)

答案 1 :(得分:0)
您可以尝试以下代码来解决您的问题:
function towerBuilder(nFloors) {
var stars = '*';
var count;
var array=[];
for (var i = 0; i<=nFloors-1; i++){
count = stars.repeat(2 * i + 1);
array.push(count);
}
return array;
}