当前位置:网站首页>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]
边栏推荐
- 教您简单几步实现工业树莓派正确安装RS232转USB驱动
- Browser Storage for H5
- 七种让盒子水平垂直居中的方法
- Introduction to Network Layer Protocols
- spark operator-parallelize operator
- Advantages of overseas servers
- The Servlet to jump to the JSP page, forwarding and redirection
- VRRP overview and experiment
- [ingress]-ingress exposes services using tcp port
- Xiaodu Xiaodu is here!
猜你喜欢

sql server duplicate values are counted after

The highlight moment of operation and maintenance starts with intelligence

transport layer protocol

单臂路由实验和三层交换机实验

LinkSLA坚持用户第一,打造可持续的运维服务方案

IP packet format (ICMP protocol and ARP protocol)

King power volume LinkSLA, realize operations engineer is happy fishing

The hook of the operation of the selenium module

监控系统的内卷,有什么讲究?

config.js相关配置汇总
随机推荐
单臂路由实验和三层交换机实验
Difference between link and @improt
Call the TensorFlow Objection Detection API for object detection and save the detection results locally
Quick question and quick answer - FAQ of Tencent Cloud Server
网络层协议介绍
Network wiring and digital-to-system conversion
RAID磁盘阵列
el-autocomplete使用
sql server 重复值在后面计数
The size of the screen adaptation
selenium模块的操作之拉钩
User and user group management, file permission management
link 和@improt的区别
LeetCode Interview Questions
Spark source code-task submission process-6.2-sparkContext initialization-TaskScheduler task scheduler
[Problem has been resolved]-Virtual machine error contains a file system with errors check forced
The method of using ROS1 bag under ROS2
el-progress实现进度条颜色不同
OpenCV3.0 is compatible with VS2010 and VS2013
7 steps to complete cloud monitoring