在JavaScript中使用0填充2D数组

时间:2016-04-04 03:00:58

标签: javascript arrays

我一直在尝试使用JavaScript填充2D数组,并且我一直在崩溃我的浏览器,所以我假设我有无限的递归,但我似乎无法找到我的错误。这是我的代码:

//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;
  }
}

2 个答案:

答案 0 :(得分:2)

当你填充数组时,你通过内循环改变i的值,并且在内循环之后没有将它改回原来的值!不要在外部和内部循环中使用相同的变量名称!

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

你真正应该做的事情:

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

答案 1 :(得分:1)

您可以使用Array#fromArray#mapArray#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);

<强>解释

var arr = Array.from({
    length: sequence1.length + 1
})
// Create an array of passed `length` of `undefined` elements

// map will iterate over all the elements of the array and update the value of each element
// Create new array and use this as the individual item in the main array
.map(() => Array.from({
    length: sequence2.length + 1
}).fill(0));