正文
- 全局对象
reverse
- 不改变原数组版,如果想要改变,那么不要deepClone
即可
javascript">Array.prototype.myReverse = function () {
const length = this.length
const arr = deepClone(this)
for (let i = 0; i < Math.floor(length / 2); i++) {
let temp = arr[i]
arr[i] = arr[length - 1 - i]
arr[length - 1 - i] = temp
}
return arr
}
const arr = ['a', 'b', 'c', 'd']
console.log(arr.myReverse());
console.log(arr)
function deepClone(target) {
if (typeof target !== 'object') {
return target
}
let result
if ({}.toString.call(target) === '[object Object]') {
result = {}
} else {
result = []
}
for (let key in target) {
if (target.hasOwnProperty(key)) {
result[key] = deepClone(target[key])
}
}
return result
}
forEach
- 兼容node环境或者浏览器环境
javascript">Array.prototype.myForEach = function (callback, thisArg = typeof global === 'undefined' ? window : global) {
for (let i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this)
}
}
filter
- 兼容node环境或者浏览器环境
- 改变原数组
javascript">Array.prototype.myFilter = function (callback, thisArg = typeof global === 'undefined' ? window : global) {
for (let i = 0; i < this.length; i++) {
if (!callback.call(thisArg, this[i], i, this)) {
this.splice(i, 1)
i--
}
}
}
map
- 兼容node环境或者浏览器环境
- 改变原数组
javascript">Array.prototype.myMap = function (callback, thisArg = typeof global === 'undefined' ? window : global) {
for (let i = 0; i < this.length; i++) {
this[i] = callback.call(thisArg, this[i], i, this)
}
}
every
some
同理,省略- 兼容node环境或者浏览器环境
javascript">Array.prototype.myEvery = function (callback, thisArg = typeof global === 'undefined' ? window : global) {
let flag = true
for (let i = 0; i < this.length; i++) {
if (!callback.call(thisArg, this[i], i, this)) {
flag = false
break
}
}
return flag
}
find
findIndex
同理,省略- 兼容node环境或者浏览器环境
javascript">Array.prototype.myFind = function (callback, thisArg = typeof window === "undefined" ? global : window) {
for (let i = 0; i < this.length; i++) {
if (callback.call(thisArg, this[i], i, this)) {
return this[i]
}
}
}
- 字符串是否是回文序列(不区分大小写)
javascript">String.prototype.isPalindrome = function () {
for (let i = 0; i < Math.floor(this.length / 2); i++) {
if (this[i].toLowerCase() !== this[this.length - 1 - i].toLowerCase()) {
return false
}
}
return true
}
String.prototype.isPalindrome = function () {
return this.toLowerCase() === this.toLowerCase().split('').reverse().join('')
}
结语
如果对你有帮助的话,请点一个赞吧