尝试使用map将字符串元素添加到数组中

时间:2016-10-12 08:30:39

标签: javascript arrays string dictionary

我尝试使用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;
 });
}

2 个答案:

答案 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;
}