I was toying a bit and was trying to instantiate a new array of length x
, where all elements of that array were initialized to a value y
:
var arr = new Array(x).fill(y);
This works well if the value of y
is anything other than an object.
Meaning that if y
is an object, the following is true:
var arr = new Array(2).fill({});
arr[0] === arr[1]; //is true;
arr[0].test = 'string';
arr[1].test === 'string'; //is also true;
Is there any way to state that a new object should be created for each element while using the fill-function? Or should I just convert it to a loop?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…