当前位置: 动力学知识库 > 问答 > 编程问答 >

Filling a 2D array with 0s in JavaScript

问题描述:

I've been trying to fill up a 2D array with JavaScript and I keep crashing my browser so I assume I have infinite recursion but I can't seem to find my error. Here's my code:

//The two sequences to compare

var sequence1 = "ATTGCTGACTTCA"

var sequence2 = "ATGCTACTA"

//Creates multi-dimensional array dependent on sequence lengths

var arr = new Array(sequence1.length + 1)

for (i = 0; i < sequence1.length + 1; i++) {

arr[i] = new Array(sequence2.length + 1);

}

//Fills array with 0s

for (i = 0; i < arr.length; i++) {

var col = i;

for (i = 0; i < arr[col].length; i++) {

arr[col][i] = 0;

}

}

网友答案:

When you filling your array, you change the value of i by inner loop, and did not change it back to it's original value after the inner loop! Dont use the same variable name in outer and inner loops!

for (i = 0; i < arr.length; i++) {
  var col = i;
  for (i = 0; i < arr[col].length; i++) {
    arr[col][i] = 0;
  }
  i = col;
}

what you realy should do:

for (i = 0; i < arr.length; i++) {
  for (j = 0; j < arr[i].length; j++) {
    arr[i][j] = 0;
  }
}
网友答案:

You can use Array#from, Array#map and Array#fill.

var arr = Array.from({
    length: sequence1.length + 1
}).map(() => Array.from({
    length: sequence2.length + 1
}).fill(0));

var sequence1 = "ATTGCTGACTTCA",
    sequence2 = "ATGCTACTA";

//Creates multi-dimensional array dependent on sequence lengths
var arr = Array.from({
    length: sequence1.length + 1
}).map(() => Array.from({
    length: sequence2.length + 1
}).fill(0));

console.log(arr);
分享给朋友:
您可能感兴趣的文章:
随机阅读: