<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>fill()填充数组方法</title>
</head>
<body>
</body>
<script>
/*
fill方法用于空数组的初始化非常方便.
数组中已有的元素,会被全部抹去.
*/
let array1 = ['a', 'b', 'c', "d"];
console.log(array1.fill(7)); // [7, 7, 7, 7]
// 创建一个有3个元素的数组,然后向其中添加文件对象
console.log(new Array(5).fill(new File([], "", {type: 'text/plain'}))); // [File, File, File, File, File]
// 使用Array.from()来达到和.fill()一样的效果
console.log(Array.from({length: 3}, () => new File([], '', {type: 'text/plain'}))); // [File, File, File]
// 如果填充的类型为对象,那么被赋值的是同一个内存地址的对象,而不是深拷贝对象
let arr1 = new Array(3).fill({name: "Mike"});
arr1[0].name = "贾飞天";
console.log(arr1); // [{name: "贾飞天"}, {name: "贾飞天"}, {name: "贾飞天"}]
let arr2 = new Array(2).fill([]);
arr2[0].push(5);
console.log(arr2); // [[5], [5], [5]]
console.error("----------------------------------");
// ⭕ 初始化一个含有若干个相同对象的数组
const newFilledList = new Array(10).fill({
name: "",
age: ""
});
/*
初始化的数组的每一个id是递增的,因此先初始化一个数组,数组中包含5个undefined元素
然后遍历元素,创建5个对象
*/
const filledList = Array.from({length: 5}).map(function(item, index) {
return {
id: index + 1,
no: "",
address: "",
sex: "",
};
});
console.log(filledList);
// ⭕更加合理的做法
const list2 = Array.from({length: 6}, (item, index) => {
return {
id: index + 1,
test1: "",
test2: "",
test3: "",
/*
此处为ES6的语法,由于属性名和属性值同名,所以可以简写为一个
由于我们初始的数组中没有元素,所以item的属性值为undefined
*/
item
}
});
console.log(list2);
/*
⭕对回调进行进一步的简化
当箭头函数返回的是一个对象的时候,这种写法会报错 (x) => {foo: x}
需要改为这种方式 x => ({foo: x})
*/
const list3 = Array.from({length: 6}, (item, index) => ({
id11: index + 1,
test11: "",
test22: "",
test33: "",
}));
console.log(list3);
/*
[
{id11: 1, test11: "", test22: "", test33: ""},
{id11: 2, test11: "", test22: "", test33: ""},
{id11: 3, test11: "", test22: "", test33: ""},
{id11: 4, test11: "", test22: "", test33: ""},
{id11: 5, test11: "", test22: "", test33: ""},
{id11: 6, test11: "", test22: "", test33: ""}
]
*/
</script>
</html>
JS数组的填充
于 2021-09-01 21:58:01 首次发布