1 Array.from
Array.from 用于将类数组转换成数组。只要有length属性
Array.from({length:3}) // [undefined, undefined, undefined]
第二个参数回调可以对数组进行map
Array.from({length:3}, val => 'kimi') // ['kimi', 'kimi', 'kimi']
2 Array.of
Array.of用于新建数组,来弥补之前构造函数Array()创建的不足。
Array() // []
Array(3) // [, , ] 一个参数代表长度
Array(1,2,3) // [1,2,3]
Array.of() // []
Array.of(3) // [3]
Array.of(1,2,3) // [1,2,3]
3 Array.keys()、 Array.values()、 Array.entries()
这三个api都用于遍历数组,返回的都是一个遍历器对象,用for of遍历。
const a = [1,2,3].keys(); // Iterator
const b = [1,2,3].values(); // Iterator
const c = [1,2,3].entries(); // Iterator
for (let [v, k] of c) {
console.log(v, k) // 0 1, 1 2, 2 3
}
console.log(a.next().value) // 0
4 Array.map
map polyfill
Array.prototype._map = function(fn, context) {
const results = [];
for (let i = 0; i < this.length; i++) {
results.push(fn.call(context, this[i], i, this));
}
return results;
}
const a = [1,2,3,45]
console.log(a._map(v => v*2));
5 Array.filter
filter polyfill
Array.prototype._filter = function(fn, context) {
const results = [];
for(let i = 0; i < this.length; i++) {
if (fn.call(context, this[i], i, this)) results.push(this[i])
}
return results;
}
const a = [1,2,3,4,5,7];
console.log(a._filter(val => val > 4));
6 Array.some()、 Array.every()
polyfill
Array.prototype._every = function(fn, context) {
for(let i = 0; i < this.length; i++) {
if (!fn.call(context, this[i], i, this)) return false;
}
return true;
}
const b = ['a', 'v', 'abc'];
const c = {a:'a'}
console.log(b._every(function(val) {
return val.indexOf(this.a) > -1
}, c))
Array.prototype._some = function(fn, context) {
for (let i = 0; i < this.length; i++) {
if (fn.call(context, this[i], i, this)) return true;
}
return false;
}
const b = ['e', 'av', 'bc'];
const c = {a:'a'}
console.log(b._some(function(val) {
return val.indexOf(this.a) > -1
}, c))
7 Array.reduce()
reduce polyfill
Array.prototype._reduce = function(fn, initVal) {
let res = initVal || Array.prototype.shift.call(this),
startI = initVal ? 0 : 1;
for (let i = startI; i < this.length; i++) {
res = fn.call(this, res, this[i], i, this);
}
return res;
}
let a = [1,2,3,4].reduce(function(memo, val, index, arr) {
return memo += val;
})
网友评论