数组新增方法Array.from() Array.fill() Array.copyWithin
Array.from(arrLike,mapFn,thisArg)
arrLike:伪数组对象或可迭代对象(必填)
mapFn:新数组中的每个元素会执行该回调函数(非必填)
thisArg:执行回调函数 mapFn 时 this 对象
作用: 1. (数组转化)将伪数组或者集合转化为真数组
例一:
<body>
<p>第一个p标签</p>
<p>第二个p标签</p>
<p>第三个p标签</p>
</body>
<script>
let p = document.getElementsByTagName("p");
console.log(p); // 图一
let arrP = Array.from(p);
console.log(arrP); // 图二
</script>
图一:
图二:
作用: 2. 数组映射(与map方法类似)浅拷贝数组
例二:
let result = Array.from([1,3,5],function(item){
return item*2
})
console.log(result) // [2, 6, 10]
Array.fill(item,start,end) 填充数组
(改变原数组)。
item:用来填充数组元素的值(必填),
start:起始索引,默认值为0,负数表示length+start(非必填),
end:终止索引,end-1,负数表示length+end(非必填)
var arr = [1, 2, 3, undefined, null];
console.log(arr.fill(0)); // [0, 0, 0, 0, 0]
console.log(arr.fill(0, 2)); // [1, 2, 0, 0, 0]
console.log(arr.fill(0, 2, 0)); // [1, 2, 3, undefined, null], 第三个参数 0 数组不变
console.log(arr.fill(0, 2, 4)); // [1, 2, 0, 0, null] 2,4表示从3,undefined区间
console.log(arr.fill(0, 2, -1)); // [1, 2, 0, 0, null], -1表示 数组长度5 -1为4
Array.copyWithin(target,start,end) 复制数组
(改变原数组,不会改变原数组的长度,只有一个参数0浅拷贝)
target: 复制到该位置。如果是负数,target 将从末尾开始计算(必填),如果target大于数组长度则不拷贝数组
start:复制元素的起始位置,负数表示从数组末尾开始(非必填),如果 start 忽略将会从0开始复制,
end: 复制元素的结束位置,end-1,负数表示从数组末尾开始(非必填),如果 end 忽略将会复制至数组结尾(默认为 arr.length)
let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
console.log(arr.copyWithin(2, 4, 10))
// 如图一位置,图二步骤
// ['a', 'b', 'e', 'f', 'g', 'h', 'i', 'j', 'i', 'j', 'k']
Array.keys() Array.values() Array.entries()
Array.keys() Array.values() Array.entries()分别对应Object.keys() Object.values() Object.entries()
let arr = ["a", "b", "c"];
for (const index of arr.keys()) {
console.log(index);
}
// 0
// 1
// 2
for (const value of arr.values()) {
console.log(value);
}
// "a"
// "b"
// "c"
for (const [index,value] of arr.entries()) {
console.log(index,value);
}
// 0 "a"
// 1 "b"
// 2 "c"
let obj = {
name : "张三",
age: 18,
gender: "male"
};
for (const index of Object.keys(obj)) {
console.log(index);
}
// name
// age
// gender
for (const value of Object.values(obj)) {
console.log(value);
}
// 张三
// 18
// male
for (const [index,value] of Object.entries(obj)) {
console.log(index,value);
}
// name 张三
// age 18
// gender male
for (const val of Object.entries(obj)) {
console.log(val);
}
// [name, "张三"]
// [age, 18]
// [gender, "male"]