var fruits = [];
fruits.push("lemon", "lemon", "lemon", "lemon");
与其推送相同的元素,不如像这样写一次:
fruits.push("lemon" * 4 times)
var fruits = [];
fruits.push("lemon", "lemon", "lemon", "lemon");
与其推送相同的元素,不如像这样写一次:
fruits.push("lemon" * 4 times)
对于原语,请使用.fill:
var fruits = new Array(4).fill('Lemon');
console.log(fruits);
对于非原语,不要使用fill,因为这样数组中的所有元素都将引用内存中的同一个对象,因此对数组中一项的更改将影响数组中的每一项。
相反,在每次迭代时显式创建对象,这可以通过以下方式完成Array.from:
var fruits = Array.from(
{ length: 4 },
() => ({ Lemon: 'Lemon' })
);
console.log(fruits);
有关如何以这种方式创建二维数组的示例:
var fruits = Array.from(
{ length: 2 }, // outer array length
() => Array.from(
{ length: 3 }, // inner array length
() => ({ Lemon: 'Lemon' })
)
);
console.log(fruits);
你不应该使用数组构造函数, 而是使用
[]。
const myArray = []; // declare array
myArray.length = 5; // set array size
myArray.fill('foo'); // fill array with any value
console.log(myArray); // log it to the console
const item = 'lemon'
const arr = Array.from({length: 10}, () => item)
const item = 'lemon'
const arr = Array.from({length: 10}, () => item)
console.log('arr', arr)