介绍
此篇属于前端算法入门系列的第一篇,主要介绍常用的数组方法、字符串方法、遍历方法、高阶函数、正则表达式以及相关数学知识。
文章主要包含以下内容:
1.数组常用方法
2.字符串常用方法
3.常用遍历方法&高阶函数
4.常用正则表达式
5.数学知识
一、数组常用方法
1.push()
在尾部追加,类似于压栈,原数组会变。
const arr = [1, 2, 3]
arr.push(8)
console.log(arr) // [1, 2, 3, 8]
2.pop()
在尾部弹出,类似于出栈,原数组会变。数组的 push & pop 可以模拟常见数据结构之一:栈。
const arr = [1, 2, 3]
const popVal = arr.pop()
console.log(popVal) // 3
console.log(arr) // [1, 2]
// 数组模拟常见数据结构之一:栈
const stack = [0, 1]
stack.push(2) // 压栈
console.log(stack) // [0, 1, 2]
const popValue = stack.pop() // 出栈
console.log(popValue) // 2
console.log(stack) // [0, 1]
3.unshift()
在头部压入数据,类似于入队,原数组会变。
const arr = [1, 2, 3]
arr.unshift(0)
console.log(arr) // [0, 1, 2, 3]
4.shift()
在头部弹出数据,原数组会变。数组的 push(入队) & shift(出队) 可以模拟常见数据结构之一:队列。
const arr = [1, 2, 3]
const shiftVal = arr.shift()
console.log(shiftVal) // 1
console.log(arr) // [2, 3]
// 数组模拟常见数据结构之一:队列
const queue = [0, 1]
queue.push(2) // 入队
console.log(queue) // [0, 1, 2]
const shiftValue = queue.shift() // 出队
console.log(shiftValue) // 0
console.log(queue) // [1, 2]
5.concat()
concat会在当前数组尾部拼接传入的数组,然后返回一个新数组,原数组不变。
const arr = [1, 2, 3]
const arr2 = arr.concat([7, 8, 9])
console.log(arr) // [1, 2, 3]
console.log(arr2) // [1, 2, 3, 7, 8, 9]
6.indexOf()
在数组中寻找该值,找到则返回其下标,找不到则返回-1。
const arr = [1, 2, 3]
console.log(arr.indexOf(2)) // 1
console.log(arr.indexOf(0)) // -1
7.includes()
在数组中寻找该值,找到则返回true,找不到则返回false。
const arr = [1, 2, 3]
console.log(arr.includes(2)) // true
console.log(arr.includes(4)) // false
8.join()
将数组转化成字符串,并返回该字符串,不传值则默认逗号隔开,原数组不变。
const arr = [1, 2, 3]
console.log(arr.join()) // ‘1, 2, 3’
console.log(arr) // [1, 2, 3]
9.toString()
将数组转化成字符串,并返回该字符串,逗号隔开,原数组不变。
const arr = [1, 2, 3, 4, 5]
console.log(arr.toString()) // ‘1, 2, 3, 4, 5’
console.log(arr) // [1, 2, 3, 4, 5]
10.reverse()
翻转原数组,并返回已完成翻转的数组,原数组改变。
const arr = [1, 2, 3]
console.log(arr.reverse(<