【问题标题】:JavaScript .join() doesn't get rid of commas in a looped multidimensional array?JavaScript .join() 没有摆脱循环多维数组中的逗号?
【发布时间】:2020-11-13 09:57:12
【问题描述】:

我对 JavaScript 和编码比较陌生,我一直在尝试通过两个 for 循环将字符串推送到一个空的多维数组中,并将输出数组转换为字符串。我的想法是将字符串添加到数组中,直到满足行和列长度。 push() 工作正常,但不知何故 join.('') 并没有摆脱内部数组中的逗号。这是我的代码(我正在codecademy中构建一个项目,输出是bash):

var rowlength = 3;
var collength = 3;

function attempt() {
  let randomarray = [];
  let i;
  let j;
  for(j = 0; j < rowlength; j++) {
    randomarray.push([]);
    for(i = 0; i < collength; i++) {
      randomarray[j].push('x');
    }
  }
    return randomarray.join('' + '\n');
};

console.log(attempt());  

输出:

x,x,x
x,x,x
x,x,x

我想要的输出:

xxx
xxx
xxx

有人可以向我解释我做错了什么吗?我已经尝试将 join('') 移到其他地方,但输出保持不变,谷歌到目前为止什么也没给我...

【问题讨论】:

  • 你也需要加入内部数组。
  • 虽然没有真正的理由让它成为一个数组开始,你可以先做randomarray.push("");然后randomarray[j] += "x";

标签: javascript for-loop multidimensional-array push


【解决方案1】:

你没有加入内部数组,一旦你完成了,最后你可以加入你已经在做的方式。在第一个循环中创建一个临时数组,然后将连接的数组推送到您的主 randomarray。现在您将拥有一个包含正确行内容的数组。

更新你的attempt 函数如下:

function attempt() {
  let randomarray = [];
  let i;
  let j;
  for(let j = 0; j < rowlength; j++) {
    let innerArray = [];
    for(let i = 0; i < collength; i++) {
      innerArray.push('x');
    }
    randomarray.push(innerArray.join(''))
  }
    return randomarray.join('' + '\n');
};

【讨论】:

  • 哦,我明白了,我怀疑我没有加入内部数组,但我无法弄清楚第二个加入的位置......它一直抛出错误。但这有帮助,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-07
  • 2014-09-05
相关资源
最近更新 更多