New Array(_).fill(object) Does Not Create New Instances Of Object
ES6 allows us to fill an Array with a certain value: function emptyRow() { return new Array(9).fill(0); } This function returns an Array of length 9, filled with only zeros: &
Solution 1:
Array#fill
won't help you, it accepts the value returned by emptyRow()
, the already created object. You could use Array#map
which accepts a function, although you won't be able to use the new Array()
constructor. Here's the simplest way:
functionemptyMatrix() {
Array.apply(null, {length: 9}).map(emptyRow);
// create the array fill in values
}
Or, more generally:
functiongenerateArray(n, valueFactory) {
returnArray.apply(null, {length: n}).map(valueFactory);
}
Solution 2:
An other solution with map():
var line = newArray(9).fill(0);
var matrix = line.map(x =>newArray(9).fill(0))
console.log(matrix);
Solution 3:
You can use Array.from()
to generate an array of specific length, and then Array.prototype.map()
to fill it with empty rows:
constemptyRow = () => Array(9).fill(0);
constgenerateArray = (n, valueFactory) => Array.from({length: 9}).map(valueFactory);
console.log(generateArray(9, emptyRow));
Solution 4:
You can use Array.from()
to create arrays of any length you want, and initialize them:
constcreateMatrix = (x, y) => Array.from({ length: x }, () =>Array.from({ length: y }, () =>0)
);
const result = createMatrix(9, 5);
console.log(result);
Solution 5:
functionemptyMatrix(length) {
var matrix = newArray();
for (var i = 0; i < length; i++)
matrix[i] = newArray(length).fill(0)
return matrix
}
console.log(emptyMatrix(5))
You can set length of your matrix
Post a Comment for "New Array(_).fill(object) Does Not Create New Instances Of Object"