当前位置:网站首页>Native JS takes you to understand the implementation and use of array methods
Native JS takes you to understand the implementation and use of array methods
2022-08-05 06:22:00 【MoXinXueWEB】
序:
巩固基础,Can help you better understand the methods of arrays,Easy to use for projects,其实,The most important thing is to prepare for the interview,哈哈哈~~
Defines an array of tests
const FootArr= [
{
name: '小龙虾', num: 999 },
{
name: '榴莲披萨', num: 888 },
{
name: '炸鸡', num: 777 },
{
name: '烤鱼', num: 666 },
{
name: '奶茶', num: 555 }
];
1. ForEach
用处:增强for循环,专门用来遍历数组和集合
Array.prototype.forEach = function (callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this)
}
}
FootArr.forEach((item, index) => {
console.log(item, index)
// {name: '小龙虾', num: 999} 0
// {name: '榴莲披萨', num: 888} 1
// {name: '炸鸡', num: 777} 2
// {name: '烤鱼', num: 666} 3
// {name: '奶茶', num: 555} 4
});
2. Map
用处:map()方法可以创建一个新数组,The result is that each element in the array is the result of calling a provided function.
Array.prototype.map = function (callback) {
const res = [];
for (let i = 0; i < this.length; i++) {
res.push(callback(this[i], i, this))
}
return res;
}
console.log(FootArr.map((item, index) => `${
item.name}--${
item.num}--${
index}`))
// ['小龙虾--999--0', '榴莲披萨--888--1', '炸鸡--777--2', '烤鱼--666--3', '奶茶--555--4']
3. Filter
用处:filter()方法会创建一个新数组,原数组的每个元素传入回调函数中,回调函数中有return返回值,Multiple return valuestrue,这个元素保存到新数组中,若返回值为false,则该元素不保存到新数组中.原数组不发生改变.
Array.prototype.filter = function (callback) {
const res = [];
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this) && res.push(this[i])
}
return res;
}
console.log(FootArr.filter(item => item.num == 666));
// [{name: '烤鱼', num: 666}]
4. Every
用处:every()方法只能遍历数组,If the conditions are met, you can jump out of the loop,返回布尔类型,一项为false就返回false,全为true则返回true.
Array.prototype.every = function (callback) {
let flag = true;
for (let i = 0; i < this.length; i++) {
flag = callback(this[i], i, this)
if (!flag) break
}
return flag;
}
console.log(FootArr.every(item => item.num >= 0)); // true
console.log(FootArr.every(item => item.num >= 1000)); // false
5. Some
用处:some()方法只能遍历数组,If the conditions are met, you can jump out of the loop,返回布尔类型,一项为true就返回true,全为false则返回false.
Array.prototype.some = function (callback) {
let flag = false;
for (let i = 0; i < this.length; i++) {
flag = callback(this[i], i, this)
if (flag) break
}
return flag;
}
console.log(FootArr.some(item => item.num == 666)); // true
console.log(FootArr.some(item => item.num >= 1000)); // false
6. Reduce
用处:reduce()方法接受一个函数作为累加器,reduce为数组中的每一个元素执行一次回调函数,不包括数组中被删除或从未被赋值的元素,接收四个参数:初始值(上一次回调的返回值),当前元素值,当前索引,原数组.
Array.prototype.reduce = function (callback, initValue) {
let pre = initValue == undefined ? this[0] : initValue;
let i = initValue == undefined ? 1 : 0;
for (i; i < this.length; i++) {
pre = callback(pre, this[i], i, this)
}
return pre
}
// 计算所有num相加 pre:上一项 next:下一项
const sum = FootArr.reduce((pre, next) => {
return pre + next.num
}, 0)
console.log(sum); // 3885
7. FindIndex
用处:findIndex()方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置.This method calls the function execution once for each element in the array:
- 当数组中的元素在测试条件时返回true是,findindex()返回符合条件的元素的索引位置,之后的值不会再调用执行函数.
- 如果没有符合条件的元素返回 -1.
Array.prototype.findIndex = function (callback) {
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
return i
}
}
return -1
}
console.log(FootArr.findIndex(item => item.name === '小龙虾')) // 0
console.log(FootArr.findIndex(item => item.name === '奶茶')) // 4
8. Find
用处:find()方法返回数组中符合测试函数条件的第一个元素
Array.prototype.find = function (callback) {
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
return this[i]
}
}
return undefined
}
console.log(FootArr.find(item => item.name === '小龙虾')) // {name: '小龙虾', num: 999}
console.log(FootArr.find(item => item.name === '哈根达斯')) // undefined
9. Fill
用处:填充数组
Array.prototype.fill = function (value, start = 0, end) {
end = (end || this.length - 1) + 1
for (let i = start; i < end; i++) {
this[i] = value
}
return this
}
console.log(FootArr.fill('蛋挞',1 ,2))
// [
// {name: '小龙虾', num: 999},
// "蛋挞",
// "蛋挞",
// {name: '烤鱼', num: 666},
// {name: '奶茶', num: 555}
// ]
console.log(FootArr.fill({
name: '蛋挞', num: 222},1 ,2))
// [
// {name: '小龙虾', num: 999},
// {name: '蛋挞', num: 222}
// {name: '蛋挞', num: 222}
// {name: '烤鱼', num: 666},
// {name: '奶茶', num: 555}
// ]
10. Includes
用处:查找元素,查到返回 true , 反之返回 false ,可查找NaN
Array.prototype.includes = function (value, start = 0) {
if (start < 0) start = this.length + start
const isNaN = Number.isNaN(value)
for (let i = start; i < this.length; i++) {
// 注意对NANThe judgment can appear twofalse的情况,So make sure of bothisNAN都是tureto match the taskNAN
if (this[i] == value || Number.isNaN(this[i]) && isNaN) {
// 注意判断NAN的情况,NAN==NAN返回false,因此只能用Number.isNAN去判断
return true
}
}
return false
}
// 第一个参数是要查找的元素
// 第二个参数表示搜索的起始位置,默认为 0 .如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为 -4 ,但数组长度为 3 ),则会重置为从 0 开始.
console.log([1, 2, 3].includes(2)) // true
console.log([1, 2, 3, NaN].includes(NaN)) // true
console.log([1, 2, 3].includes(1, 1)) // false
console.log([1, 2, 3].includes(4)) // false
11. Join
用处:将数组用分隔符拼成字符串,分隔符默认为 “,”
Array.prototype.join = function (s = ',') {
let str = ''
for(let i = 0; i < this.length; i++) {
str = i === 0 ? `${
str}${
this[i]}` : `${
str}${
s}${
this[i]}`
}
return str
}
console.log([1, 2, 3].join()) // 1,2,3
console.log([1, 2, 3].join('*')) // 1*2*3
12. Flat
用处:Convert a multidimensional array to a single-dimensional array
Array.prototype.flat = function () {
let arr = this
while (arr.some(item => Array.isArray(item))) {
// concat() 方法用于连接两个或多个字符串
arr = [].concat(...arr)
}
return arr
}
const testArr = [1, [2, 3, [4, 5]], [8, 9]]
console.log(testArr.flat()) // [1, 2, 3, 4, 5, 8, 9]
边栏推荐
- H5 的浏览器存储
- This is indeed the best article on microservice architecture I have read!
- Small example of regular expression--validate email address
- One-arm routing experiment and three-layer switch experiment
- From "dual card dual standby" to "dual communication", vivo took the lead in promoting the implementation of the DSDA architecture
- markdown editor template
- [问题已处理]-虚拟机报错contains a file system with errors check forced
- Spark source code-task submission process-6.2-sparkContext initialization-TaskScheduler task scheduler
- [问题已处理]-jenkins流水线checkout超时
- By solving these three problems, the operation and maintenance efficiency will exceed 90% of the hospital
猜你喜欢
随机推荐
智能运维会取代人工运维吗?
Mina断线重连
spark operator - map vs mapPartitions operator
深度 Zabbix 使用指南——来自惨绿少年
spark operator-textFile operator
The problem come from line screening process
增长:IT运维发展趋势报告
网络不通?服务丢包?看这篇就够了
Four ways to obtain Class objects through reflection
static routing
js dynamically get screen width and height
spark operator-parallelize operator
正则表达式小实例--验证邮箱地址
Spark source code - task submission process - 4-container to start executor
Billions of IT operations in the market, the product by strength to speak
Programmers should understand I/O this way
By solving these three problems, the operation and maintenance efficiency will exceed 90% of the hospital
Tencent greetings function SCF - entry instructions
[问题已处理]-虚拟机报错contains a file system with errors check forced
link 和@improt的区别