切换主题
数组方法
更具体的实现,推荐查看
ECMAScript
源码中对应方法的实现,传送门Array
。
Array.of()
JavaScript
if (!Array.of) {
Array.of = function () {
return Array.prototype.slice.call(arguments)
// return [].slice.call(arguments)
}
}
Array.isArray()
JavaScript
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]'
// return ({}).toString.call(arg) === '[object Array]'
}
}
Array#concat()
JavaScript
if (!Array.prototype.concat) {
Array.prototype.concat = function (arr1, ...arrs) {
let ret = Array.isArray(arr1) ? arr1.slice() : Array.of(arr1)
ret.push.apply(ret, arrs)
// ret.push.call(ret, ...arrs)
// ret.push.bind(ret, ...arrs)()
return ret
}
}
Array#flat()
JavaScript
if (!Array.prototype.flat) {
Array.prototype.flat = function flat(arr, dep = 1) {
let _dep = 1
function _flat(arr, dep, _dep) {
return arr.reduce(function (acc, cur) {
return acc.concat(Array.isArray(cur) && (dep === Infinity || _dep < dep)
? flat(cur, dep, _dep + 1)
: cur)
}, [])
}
return _flat(arr, dep, _dep)
}
}
Array#pop()
JavaScript
if (!Array.prototype.pop) {
Array.prototype.pop = function () {
return this.splice(this.length - 1, 1)[0]
}
}
Array#shift()
JavaScript
if (!Array.prototype.shift) {
Array.prototype.shift = function () {
return this.splice(0, 1)[0]
}
}
Array#push()
JavaScript
if (!Array.prototype.push) {
Array.prototype.push = function () {
this.splice.apply(this, [this.length, 0].concat([].slice.apply(arguments)))
return this.length
}
}
Array#unshift()
JavaScript
if (!Array.prototype.unshift) {
Array.prototype.unshift = function () {
this.splice.apply(this, [0, 0].concat([].slice.apply(arguments)))
return this.length
}
}