带你读《现代Javascript高级教程》四、JavaScript数组(2)https://developer.aliyun.com/article/1349684?groupCode=tech_library
实现数组遍历的方法
// 模拟实现 forEach() 方法Array.prototype.myForEach = function(callbackFn) { for (let i = 0; i < this.length; i++) { callbackFn(this[i], i, this); }}; // 模拟实现 map() 方法Array.prototype.myMap = function(callbackFn) { const mappedArray = []; for (let i = 0; i < this.length; i++) { mappedArray.push(callbackFn(this[i], i, this)); } return mappedArray;}; // 示例使用const myArray = [1, 2, 3]; myArray.myForEach((value, index) => { console.log(`Element at index indexis{index} is {value}`);}); const doubledArray = myArray.myMap(value => value * 2); console.log(doubledArray); // 输出:[2, 4, 6]
实现数组转换和连接的方法
// 模拟实现 toString() 方法Array.prototype.myToString = function() { let result = ''; for (let i = 0; i < this.length; i++) { if (i > 0) { result += ', '; } result += this[i]; } return result;}; // 模拟实现 join() 方法Array.prototype.myJoin = function(separator = ',') { let result = ''; for (let i = 0; i < this.length; i++) { if (i > 0) { result += separator; } result += this[i]; } return result;}; // 示例使用const myArray = [1, 2, 3]; console.log(myArray.myToString()); // 输出:'1, 2, 3' console.log(myArray.myJoin('-')); // 输出:'1-2-3'
实现数组排序和搜索的方法
// 模拟实现 sort() 方法Array.prototype.mySort = function(compareFn) { const length = this.length; for (let i = 0; i < length - 1; i++) { for (let j = 0; j < length - 1 - i; j++) { if (compareFn(this[j], this[j + 1]) > 0) { [this[j], this[j + 1]] = [this[j + 1], this[j]]; } } } return this;}; // 模拟实现 indexOf() 方法Array.prototype.myIndexOf = function(searchElement, fromIndex = 0) { const length = this.length; for (let i = Math.max(fromIndex, 0); i < length; i++) { if (this[i] === searchElement) { return i; } } return -1;}; // 示例使用const myArray = [5, 2, 1, 4, 3]; console.log(myArray.mySort()); // 输出:[1, 2, 3, 4, 5] console.log(myArray.myIndexOf(4)); // 输出:3
实现其他常用方法
// 模拟实现 isArray() 方法 Array.myIsArray = function(obj) { return Object.prototype.toString.call(obj) === '[object Array]';}; // 模拟实现 find() 方法Array.prototype.myFind = function(callbackFn) { for (let i = 0; i < this.length; i++) { if (callbackFn(this[i], i, this)) { return this[i]; } } return undefined;}; // 示例使用const myArray = [1, 2, 3, 4, 5]; console.log(Array.myIsArray(myArray)); // 输出:true console.log(myArray.myFind(value => value > 3)); // 输出:4
以上是一些简单的模拟实现示例,用于帮助理解数组方法的实现原理。
带你读《现代Javascript高级教程》四、JavaScript数组(4)https://developer.aliyun.com/article/1349682?groupCode=tech_library