数组进阶2
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>es6</p>
<p>es6</p>
<p>慕课网</p>
</body>
<script src="/数组/0410.js"></script>
</html>
js部分
{
let arr = Array.of(3, 4, 7, 9, 11);
console.log('arr', arr);
let empty = Array.of();
console.log('empty', empty);
}
{
let p = document.querySelectorAll('p');
let pArr = Array.from(p);
pArr.forEach(function (item) {
console.log(item.textContent);
});
console.log(Array.from([1, 3, 5],
function (item) {
return item * 2;
}));
} {
console.log('fill-7', [1, 'a', undefined].fill(7));
console.log('fill,pos', ['a', 'b', 'c'].fill(7, 1, 3)); //从起始1开始,3是长度
} {
for (let index of ['1', 'c', 'ks'].keys()) {
console.log('keys', index);
}
for (let value of ['1', 'c', 'ks'].values()) {
console.log('values', value);
}
for (let [index, value] of ['1', 'c', 'ks'].entries()) {
console.log('values', index, value);
}
} {
//指定的元素替换掉指定的位置
console.log([1, 2, 3, 4, 5].copyWithin(0, 3, 4));
//0的位置替换成从3的起始位置的值从4截止的位置(不取4的数)
} {
//查找
console.log([1, 2, 3, 4, 5, 6].find(function (item) {
return item > 3; //找出一个就可以了
}));
console.log([1, 2, 3, 4, 5, 6].findIndex(function (item) {
return item > 3; //找出一个,返回下标
}));
} {
console.log('number', [1, 2, NaN].includes(1)); //看数组中是不是包括1,是就返回true
console.log('number', [1, 2, NaN].includes(NaN));
}
/**
* 扩展Array.prototype
* 增加insert、remove、replace方法
*/
Array.prototype.remove = function (index, len) {
this.splice(index, len);
return this;
};
//arr为要插入的数据数组。
Array.prototype.insert = function (index, arr) {
this.splice(index, 0, ...arr);
return this;
};
//arr为要替换的数据数组。
Array.prototype.replace = function (index, arr) {
this.splice(index, arr.length, ...arr);
return this;
};