push方法 在数组最后加入新值
改变原数组 返回新数组的长度
const arr = [1, "2", true, [3, 4], undefined, null];
const res = arr.push("5", "6");
console.log(arr); //[ 1, '2', true, [ 3, 4 ], undefined, null, '5', '6' ]
console.log(res); //8
//实现原理
Array.prototype.myPush = function (...items) {
for (let i = 0; i < items.length; i++) {
this[this.length] = items[i];
}
// this.length = this.length + items.length;
return this.length; // 返回数组的长度
};
let res = [1, 2, 3, 4, 5];
res.myPush(6, 7, 8);
console.log(res);
pop方法 在数组最后删除值
改变原数组 返回最后删除的值
const arr = [1, "2", true, [3, 4], undefined, null];
const res = arr.pop();
console.log(arr); //[ 1, '2', true, [ 3, 4 ], undefined ]
console.log(res); //null
//实现原理
Array.prototype.myPop = function () {
let res = this[this.length - 1];
// 删除最后一个元素
this.length--;
// 返回最后一个元素
return res;
};
shift方法 在数组开始删除值
改变原数组 返回删除值
const arr = [1, "2", true, [3, 4], undefined, null];
const res = arr.shift();
console.log(arr); //['2', true, [ 3, 4 ], undefined ]
console.log(res); // 1
//实现原理
Array.prototype.MyShift = function () {
if (this.length === 0) { // 空数组直接返回 undefined
return undefined;
}
const firstElement = this[0]; // 获取第一个元素的值
for (let i = 0; i < this.length - 1; i++) {
this[i] = this[i + 1]; // 将后面的元素依次向前移动一位
}
this.length--; // 修改数组长度,删除最后一个元素
return firstElement;
};
unshift方法 在数组开头加入新值
改变原数组 返回新数组的长度
const arr = [1, "2", true, [3, 4], undefined, null];
const res = arr.unshift(0);
console.log(arr); //[ 0, 1, '2', true, [ 3, 4 ], undefined, null ]
console.log(res); // 7
//实现原理
Array.prototype.myUnshift = function (...items) {
for (let i = 0; i < items.length; i++) {
// 在数组开头插入元素
for (let j = this.length - 1; j >= 0; j--) {
// 将元素依次向后移动一位
this[j + 1] = this[j];
}
this[0] = items[i]; // 在开头插入新元素
}
return this.length; // 返回修改后数组的新长度
};
slice方法不改变原数组
slice() 方法用于从数组中截取指定位置的元素,返回一个新的数组。
语法是array.slice(start?, end?), 截取包括start元素 不包括end元素
const arr = [1, "2", true, [3, 4], undefined, null];
const res= names.slice(2,5);
const res1 = arr.slice(7);
console.log(res) [ true, [ 3, 4 ], undefined ]
console.log(res1); // []
//slice实现原理
Array.prototype.selfSlice = function (start, end) {
if (start < 0 || start > this.length) return [];
if (end < 0 || end > this.length) end = this.length;
let result = [];
for (let i = start; i < end; i++) {
result.push(this[i]);
}
return result;
};
splice方法改变原数组
splice()方法用于从数组中删除、替换或添加元素,并返回被删除的元素组成的数组,
语法是array.splice(start, deleteCount?,…items?) ,删除包括start元素
const arr = [1, "2", true, [3, 4], undefined, null];
const arr1 = arr.splice(1, 2, "siu", 4, 5, 8);
console.log(arr); //[ 1, 'siu', 4, 5, 8, [ 3, 4 ], undefined, null ]
console.log(arr1); //[ '2', true ]
//实现原理
Array.prototype.SelfSplice = function (start, deleteCount, ...items) {
let deleted = [];
console.log(items);
let DeleteCountIndexlength = start + deleteCount;
// DeleteCountIndexlength > this.length ? this.length : DeleteCountIndexlength;
DeleteCountIndexlength = Math.min(DeleteCountIndexlength, this.length);
// 保存返回值,并删除原数组数据
for (let i = start; i < DeleteCountIndexlength; i++) {
deleted.push(this[i]);
delete this[i];
}
// 移动剩余元素
for (let i = start + deleteCount; i < this.length; i++) {
this[i - deleteCount + items.length] = this[i];
}
// 插入元素到指定位置
for (let i = 0; i < items.length; i++) {
this[start + i] = items[i];
}
// 更新length
this.length = this.length - deleteCount + items.length;
return deleted;
};
const arr = [1, "2", true, [3, 4], undefined, null];
const arr1 = arr.SelfSplice(1, 3, 44, 55, 66);
console.log(arr1);
console.log(arr);
//...deletedcount和items长度 不一致出现bug
find方法
find方法用于返回数组中满足条件的第一个元素,没有找到目标则返回undefined
语法是array.find(callback(value,index?,array?), thisArg?) thisArg
参数允许你控制回调函数中的 this
值,从而影响函数的上下文。 callback函数应返回一个布尔值
const arr = [11, 22, 33, 44];
let arr1 = arr.myfind((item) => {
return item > 32;
});
console.log(arr1); // 33
// 原理实现
Array.prototype.selfFind= function (callback,thisArg = this) {
for (let i = 0; i < this.length; i++) {
if (callback.call(thisArg,this[i], i, this)) {
return this[i]
}
}
return undefined;
};
findIndex方法
findIndex方法用于返回数组中满足条件的第一个元素的索引,没有索引返回 -1,
语法是array.find(callback(value ,index?,array?), thisArg?) callback函数应返回一个布尔值
const arr = [11, 22, 33, 44];
let arr1 = arr.myfindIndex((item) => {
return item > 32;
});
console.log(arr1); // 3
Array.prototype.myfindIndex = function (callback,thisArg = this) {
for (let i = 0; i < this.length; i++) {
if (callback.call(thisArg,this[i], i, this)) {
return i;
}
}
return -1;
};
indexOf方法用于返回指定元素在数组中第一次出现的索引。没有找到返回 -1
语法是array.indexOf(searchElement , fromindex?) fromIndex开始查找的索引位置,默认为 0。
Array.prototype.indexOf = function (serachElement, fromIndex = 0) {
for (let i = fromIndex; i < this.length; i++) {
if (this[i] === serachElement) {
return i;
}
return -1;
}
};
indexOf方法用于返回指定元素在数组中最后一次出现的索引。没有找到返回 -1
语法是array.indexOf(searchElement , fromindex?) fromIndex开始查找的索引位置,默认为最后一个元素索引
Array.prototype.myLastIndexOf = function (
serachElement,
fromIndex = this.length - 1
) {
for (let i = fromIndex; i >= 0; i--) {
if (this[i] === serachElement) {
return i;
}
}
return -1;
};
const arr = [11, 22, 33, 44, 55, 11];
const res = arr.myLastIndexOf(11);
console.log(res);
includes
includes方法用于判断数组是否包含指定元素。
语法是array.includes(searchElement,fromIndex?) 返回布尔值
Array.prototype.myIncludes = function (serachElement, fromIndex = 0) {
for (let i = fromIndex; i < this.length; i++) {
if (this[i] === serachElement) {
return true;
}
return false;
}
};
const arr = [11, 22, 33, 44, 55, 11];
const res = arr.myIncludes(11);
console.log(res);
forEach
forEach方法用于对数组中的每个元素执行指定的回调函数。
语法是array.forEach(callback(value, index, array),thisArg )
const Football = [
{ name: "messi", num: 36 },
{ name: "peli", num: 23 },
{ name: "Maradona", num: 33 },
{ name: "Ronaldo", num: 38 },
];
Array.prototype.myforEach = function (callback, thisArg = this) {
for (let i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this);
}
};
Football.forEach()
Football.myforEach((item, index) => {
console.log(item, index);
});
map
map方法可以对数组中的每个元素都执行指定的回调函数,然后返回一个新的数组,新数组中的每个元素都是通过回调函数的返回值得到的
语法是array.map(callback(value, index, array),thisArg )
const Football = [
{ name: "messi", num: 36 },
{ name: "peli", num: 23 },
{ name: "Maradona", num: 33 },
{ name: "Ronaldo", num: 38 },
];
//实现原理
Array.prototype.myMap = function (callback, thisArg = this) {
const res = [];
for (let i = 0; i < this.length; i++) {
res.push(callback.call(thisArg, this[i], i, this));
}
return res;
};
let res = Football.myMap((item) => {
return `${item.name} ${item.num}`;
});
console.log(res);
filter
filter用法可以根据指定的回调函数对数组中的每个元素进行过滤,并返回一个新的数组,新数组中只包含满足回调函数条件的元素
语法array.filter(callback(value ,index?,array?),thisArg?)
const Football = [
{ name: "messi", num: 36 },
{ name: "peli", num: 23 },
{ name: "Maradona", num: 33 },
{ name: "Ronaldo", num: 38 },
];
Array.prototype.myFilter = function (callback, thisArg = this) {
const res = [];
for (let i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this) && res.push(this[i]);
}
return res;
};
const res = Football.myFilter((item) => {
return item.num > 35;
});
console.log(res);
every
every用于检测数组中的所有元素是否都满足回调函数的条件,回调函数返回值为布尔值
语法array.every(callback(value ,index?,array?),thisArg?)
const Football = [
{ name: "messi", num: 36 },
{ name: "peli", num: 23 },
{ name: "Maradona", num: 33 },
{ name: "Ronaldo", num: 38 },
];
Array.prototype.myEvery = function (callback, thisArg = this) {
let flag = false;
for (let i = 0; i < this.length; i++) {
flag = callback.call(thisArg, this[i], i, this);
if (!flag) break;
}
return flag;
};
const res = Football.myEvery((item) => item.num >= 30);
const res1 = Football.myEvery((item) => item.num >= 20);
console.log(res); //false
console.log(res1); //true
some
some用于检测数组中是否至少有一个元素满足回调函数的条件,回调函数返回值为布尔值
语法array.every(callback(value ,index?,array?),thisArg?)
const Football = [
{ name: "messi", num: 36 },
{ name: "peli", num: 23 },
{ name: "Maradona", num: 33 },
{ name: "Ronaldo", num: 38 },
];
Array.prototype.mySome = function (callback, thisArg = this) {
let flag = false;
for (let i = 0; i < this.length; i++) {
flag = callback.call(thisArg, this[i], i, this);
if (flag) break;
}
return flag;
};
const res = Football.mySome((item) => item.num > 22);
const res1 = Football.mySome((item) => item.num > 38);
console.log(res);
console.log(res1);
reduce
reduce 方法将数组中的所有元素通过回调函数进行累积计算。
语法是Array.reduce(callback(previousValue ,currentValue, currentIndex?,array?),initialValue?) previousValue累计值,即上一次回调函数的返回值或初始值,currentValue当前正在处理的数组元素,initialValue 初始值
const Football = [
{ name: "messi", num: 36 },
{ name: "peli", num: 23 },
{ name: "Maradona", num: 33 },
{ name: "Ronaldo", num: 38 },
];
Array.prototype.myReduce = function (callback, ...args) {
let start = 0;
let pre = this[0];
if (args) {
pre = args[0];
} else {
start = 1;
}
for (let i = start; i < this.length; i++) {
pre = callback(pre, this[i], i, this);
}
return pre;
};
const res = Football.myReduce((prev, next) => {
console.log(prev, next.num, next.name);
return prev + next.num;
}, 1);
console.log(res);
reduceRight 跟reduce类似 只不过是从数组的最后一个元素开始迭代
//实现原理
Array.prototype.myReduceRight = function (callback, ...args) {
let start = this.length;
let pre = this[this.length - 1];
if (args) {
pre = args[0];
} else {
start = this.length - 2;
}
for (let i = start; i >= 0; i--) {
pre = callback(pre, this[i], i, this);
}
return pre;
};
sort
sort用来对数组进行排序和翻转操作
Array.sort(compareFn?) 默认情况下,sort()
方法会将数组元素转换为字符串,然后按照 Unicode 编码进行排序。如果需要按照其他规则排序(例如数字大小),则需要提供自定义的比较函数。
//
let arr = [2, 4, 8, 6, 1, 3, 5, 7, 10, 11];
let arr1 = [2, 4, 8, 6, 1, 3, 5, 7, 10, 11];
let arr2 = [2, 4, 8, 6, 1, 3, 5, 7, 10, 11];
let res = arr.sort();
let res1 = arr1.sort((a, b) => a - b);
let res2 = arr2.sort((a, b) => b - a);
console.log(res);
console.log(res1);
console.log(res2);
reverse
reverse用来对数组进行翻转操作
Array.reverse()会修改原数组
// 实现原理
Array.prototype.myReverse = function () {
for (let i = 0; i < this.length / 2; i++) {
let temp = this[i];
this[i] = this[this.length - 1 - i];
this[this.length - 1 - i] = temp;
}
return this;
};
let arr = [1, 2, 3, 4, 5, 6];
arr.reverse();
console.log(arr);
fill
fill用于将数组中的所有元素替换为指定的固定值。
语法array.fill(value, start?, end?) 不包括end索引
const Football = [
{ name: "messi", num: 36 },
{ name: "peli", num: 23 },
{ name: "Maradona", num: 33 },
{ name: "Ronaldo", num: 38 },
];
Array.prototype.myfill = function (value, start = 0, end) {
if (end > this.length || !end) end = this.length;
for (let i = start; i < end; i++) {
this[i] = value;
}
return this;
};
let res = Football.myfill({ name: "tenghahe", num: 55 }, 1, 2);
console.log(res);
/*[
{ name: 'messi', num: 36 },
{ name: 'tenghahe', num: 55 },
{ name: 'Maradona', num: 33 },
{ name: 'Ronaldo', num: 38 }
]*/
join
join用来将每个元素转换为字符串,并使用指定的分隔符连接它们。
join语法 join(separator?) 默认为","分割
Array.prototype.myJoin = function (s = ",") {
let result = "";
for (let i = 0; i < this.length; i++) {
result += String(this[i]);
if (i !== this.length - 1) {
result += s;
}
}
return result;
};
fruits.join()
const fruits = ["apple", "banana", "orange"];
const result = fruits.myJoin("-");
const result1 = fruits.myJoin("*");
const result2 = fruits.myJoin();
console.log(result); // 输出 "apple-banana-orange"
console.log(result1); // 输出 "apple-banana-orange"
console.log(result2); // 输出 "apple-banana-orange"
concat
concat用于合并两个或多个数组,并返回一个新的数组,而不会修改原始数组。
语法array.concat(…arr)
Array.prototype.myConcat = function (...args) {
let res = this;
for (let i = 0; i < args.length; i++) {
let currentElement = args[i];
if (Array.isArray(currentElement)) {
for (let i = 0; i < currentElement.length; i++) {
res.push(currentElement[i]);
}
} else {
res.push(currentElement);
}
}
return res;
};
let res = [1, 2, 3];
let res1 = [4, 5, 6];
let res2 = [7, 8, 9];
const result = res.myConcat(res1, res2);
console.log(result);
flat
flat用于将多维数组扁平化为一维数组,它会将嵌套的数组展开,并返回一个新的一维数组。
Array.prototype.myFlat = function (depth = 1) {
let res = [];
for (let i = 0; i < this.length; i++) {
const item = this[i];
if (Array.isArray(item) && depth > 0) {
res.push(...item.myFlat(depth - 1));
} else {
res.push(item);
}
}
return res;
};
const textArr = ["11", "banana", "orange", ["1", "1", "3", "3", ["j"]]];
let res = textArr.myFlat(2);
console.log(res);
/*
[
'11', 'banana',
'orange', '1',
'1', '3',
'3', 'j'
]
*/
flatMap
flatMap结合了 map()
和 flat()
两个方法的功能。它首先对数组中的每个元素执行一个映射函数,然后将结果展开为一维数组。
语法Array.flatMap(callback(value,index?,array?),thisArg?)
Array.prototype.myFlatMap = function (callback, thisArg = this) {
let res = [];
for (let i = 0; i < this.length; i++) {
let mapped = callback.call(thisArg, this[i], i, this);
for (let i = 0; i < mapped.length; i++) {
if (Array.isArray(mapped[i])) {
res.push(...mapped[i]);
} else {
res.push(mapped[i]);
}
}
}
return res;
};
let arr = [1,2,3]
let res = arr.myFlatMap((item) => {
return [item, item * 2];
});
console.log(res);
toString
toString用于将数组转换为字符串 返回新字符串
Array.prototype.myToString = function() {
let res = '';
for (let i = 0; i < this.length; i++) {
if (i > 0) {
res += ',';
}
res += this[i];
}
return res;
}
const arr = [1, 2, 3];
console.log(arr.myToString()); // "1,2,3"
toLocaleString
toLocaleString用于数组转换为字符串形式,根据本地化设置进行格式化的字符串表示。
语法Array.toLocaleString(locales?,option?) 返回字符串
const number = 12345.6789;
console.log(number.toLocaleString()); // 根据环境输出:12,345.679 或 12.345,679
console.log(number.toString()); //12345.6789
const date = new Date();
console.log(date.toLocaleString()); // 根据环境输出:1/13/2024, 2:25:46 PM 或 2024/1/13 下午2:25:46
console.log(date.toString()); //Sun Jan 14 2024 00:15:24 GMT+0800 (中国标准时间)
const currency = 12345.67;
console.log(
currency.toLocaleString("en-US", { style: "currency", currency: "USD" })
); // 输出:$12,345.67
console.log(currency.toString()); //12345.67
const percent = 0.75;
console.log(percent.toLocaleString("en-US", { style: "percent" })); // 输出:75%
console.log(percent.toString()); // 输出:0.75
//`toString()` 方法返回的是标准的字符串表示,而 `toLocaleString()` 方法返回的是根据本地化设置进行格式化的字符串表示。
copyWithin
copyWithin数组内部将指定范围的元素拷贝到另一个位置。copyWithin()
方法不会改变数组的长度,但会修改原始数组。
语法Array.copyWithin(target,start?end?)start默认为0,end默认为length,改变元素
Array.prototype.myCopyWithin = function (target, start = 0, end = this.length) {
const sourceStart = start < 0 ? this.length + start : start;
const sourceEnd = end < 0 ? this.length + end : end;
// 创建一个数组用于存储结果
let count = Math.min(sourceEnd - sourceStart, this.length - target);
// 遍历原始数组
for (let i = 0; i < count; i++) {
this[target + i] = this[sourceStart + i];
}
return this;
};
const array = [1, 2, 3, 4, 5];
const result = array.myCopyWithin(2, 4, 5);
console.log(result); // 输出:[1, 2, 5, 4, 5]
console.log(array); // 输出:[1, 2, 5, 4, 5]
values返回一个新的迭代器对象,它包含数组中所有元素的值
Array.prototype.myValues = function () {
let i = 0;
return {
next: () => {
if (i < this.length) {
return { value: this[i++], done: false };
} else {
return { value: undefined, done: true };
}
},
};
};
const array1 = ["a", "b", "c"];
const iterator = array1.myValues();
console.log(iterator.next()); // { value: "a", done: false }
console.log(iterator.next()); // { value: "b", done: false }
console.log(iterator.next()); // { value: "c", done: false }
console.log(iterator.next()); // { value: undefined, done: true }
keys
keys返回一个新的迭代器对象,它包含数组中所有索引的值
Array.prototype.myKeys = function () {
let i = 0;
return {
next: () => {
if (i < this.length) {
return { value: i++, done: false };
} else {
return { value: undefined, done: true };
}
},
};
};
entries
entries方法返回一个新的迭代器对象,该对象包含数组中所有元素的键值对。
Array.prototype.myEntries= function () {
let i = 0;
return {
next: () => {
if (i < this.length) {
return { value: [i, this[i++]], done: false };
} else {
return { value: undefined, done: true };
}
},
};
};
const arr = ["a", "b", "c"];
// 使用 Array.prototype.at() 方法访问数组元素
console.log(arr.at(0)); // 输出 'a'
console.log(arr.at(1)); // 输出 'b'
console.log(arr.at(2)); // 输出 'c'
console.log(arr.at(3)); // 输出 undefined
// console.log(arr.at(4)); // 输出 undefined
// 使用传统的方括号语法访问数组元素
console.log(arr[0]); // 输出 'a'
console.log(arr[1]); // 输出 'b'
console.log(arr[2]); // 输出 'c'
console.log(arr[3]); // 输出 undefined
console.log(arr[4]); // 输出 undefined
// 访问超出数组范围的索引时,两种方法的行为有所不同
//使用传统的方括号语法时,可能会导致越界错误
//at返回值为 `undefined`
//使用 `Array.prototype.at()` 方法可以提高代码的健壮性和可靠性,同时避免可能会导致错误的行为
文章到这里就结束了,希望对你有所帮助,谢谢大家。