一、函数相关
1、call()& apply()& bind()
1.1、自定义函数对象的call方法
call.js
/*
自定义函数对象的call方法
Fn:要执行的函数
obj:函数运行时this指向的对象
args:函数运行时的参数
*/
function call(Fn, obj, ...args) {
// 如果obj是undefined/null, this指定为window
if (obj === undefined || obj === null) {
// return fn(...args)
obj = window
}
// 给obj添加一个临时方法, 方法指向的函数就是fn
obj.tempFn = Fn;//tempFn内部在执行时this是指向obj的,变相实现了this指向obj这样一个效果
// 通过obj来调用这个方法 ==> 也就会执行fn函数 ==> 此时fn中的this肯定为obj
const result = obj.tempFn(...args);
// 删除obj上的临时方法
delete obj.tempFn;
// 返回fn执行的结果
return result;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
<script src="./call.js"></script>
</head>
<body>
<script>
// 声明一个函数
function add(a, b) {
return a + b + this.c;
}
// 声明一个对象
let obj = {
c: 521
}
//添加全局属性
window.c = 1314;
// 执行call函数
console.log(call(add, obj, 10, 20));// 151
console.log(call(add, null, 30, 40));// 1384
</script>
</body>
</html>
1.2、自定义函数对象的apply方法
/*
自定义函数对象的Apply方法
Fn:要执行的函数
obj:函数运行时this指向的对象
args:函数运行时的参数
*/
// 改变this的指向,执行函数,返回结果
function apply(Fn, obj, ...args) {
if (obj === undefined || obj === null) {
obj = window;
}
//给obj添加一个临时的方法,方法指向的函数就是Fn
obj.tempFn = Fn;
// 通过obj来调用这个方法 ==> 也就会执行fn函数 ==> 此时fn中的this肯定为obj
const result = obj.tempFn(...args)
// 删除obj上的临时方法
delete obj.tempFn
// 返回fn执行的结果
return resultv
}
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
<script src="./call.js"></script>
</head>
<body>
<script>
// 声明一个函数
function add(a, b) {
return a + b + this.c;
}
// 声明一个对象
let obj = {
c: 521
}
//添加全局属性
window.c = 1314;
// 执行call函数
console.log(apply(add, obj, 10, 20));// 151
console.log(apply(add, null, 30, 40));// 1384
</script>
</body>
</html>
1.3、自定义函数对象的bind方法
import {call} from './call'
/*
自定义函数对象的bind方法
*/
export function bind(fn, obj, ...args) {
console.log('bind()')
// 返回一个新函数
return (... args2) => {
// 通过call调用原函数, 并指定this为obj, 实参为args与args2
return call(fn, obj, ...args, ...args2)
}
}
2、函数节流与函数防抖
2.1. 相关理解
-
区别函数节流与防抖
2.2.API说明
2.3.编码实现
throttle.js
: 函数节流
/*
实现函数节流
- 语法: throttle(callback, wait)
- 功能: 创建一个节流函数,在 wait 毫秒内最多执行 `callback` 一次
*/
export function throttle(callback, wait) {
let start = 0
// 返回一个事件监听函数(也就是节流函数)
return function (event) {
console.log('throttle event')
// 只有当距离上次处理的时间间隔超过了wait时, 才执行处理事件的函数
const current = Date.now()
if ( current - start > wait) {
callback.call(this, event) // 需要指定this和参数
start = current
}
}
}
debounce.js
: 函数防抖
/*
实现函数防抖
- 语法: debounce(callback, wait)
- 功能: 创建一个防抖动函数,该函数会从上一次被调用后,延迟 `wait` 毫秒后调用 `callback`
*/
export function debounce (callback, wait) {
// 用来保存定时器任务的标识id
let timeoutId = -1
// 返回一个事件监听函数(也就是防抖函数)
return function (event) {
console.log('debounce event')
// 清除未执行的定时器任务
if (timeoutId!==-1) {
clearTimeout(timeoutId)
}
// 启动延迟 await 时间后执行的定时器任务
timeoutId = setTimeout(() => {
// 调用 callback 处理事件
callback.call(this, event)
// 处理完后重置标识
timeoutId = -1
}, wait)
}
}
应用
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
<script src="./utils.js"></script>
</head>
<body>
<button id="handle">正常处理</button>
<button id="throttle">测试函数节流</button>
<button id="debounce">测试函数防抖</button>
<script>
/* 处理点击事件的回调函数 */
function handleClick(event) { // 处理事件的回调
console.log('处理点击事件', this, event)
}
document.getElementById('handle').onclick = handleClick
document.getElementById('throttle').onclick = throttle(handleClick, 2000)
document.getElementById('debounce').onclick = debounce(handleClick, 2000)
</script>
</body>
</html>
二、数组相关
1、API列表
2、数组声明式系列方法
2.1.使用数组声明式系列方法
2.2.编码实现
declares.js
: 实现数组声明式处理系列工具函数
/*
实现map()
*/
export function map (array, callback) {
const arr = []
for (let index = 0; index < array.length; index++) {
// 将callback的执行结果添加到结果数组中
arr.push(callback(array[index], index))
}
return arr
}
/*
实现reduce()
*/
export function reduce (array, callback, initValue) {
let result = initValue
for (let index = 0; index < array.length; index++) {
// 调用回调函数将返回的结果赋值给result
result = callback(result, array[index], index)
}
return result
}
/*
实现filter()
*/
export function filter(array, callback) {
const arr = []
for (let index = 0; index < array.length; index++) {
if (callback(array[index], index)) {
arr.push(array[index])
}
}
return arr
}
/*
实现find()
*/
export function find (array, callback) {
for (let index = 0; index < array.length; index++) {
if (callback(array[index], index)) {
return array[index]
}
}
return undefined
}
/*
实现findIndex()
*/
export function findIndex (array, callback) {
for (let index = 0; index < array.length; index++) {
if (callback(array[index], index)) {
return index
}
}
return -1
}
/*
实现every()
*/
export function every (array, callback) {
for (let index = 0; index < array.length; index++) {
if (!callback(array[index], index)) { // 只有一个结果为false, 直接返回false
return false
}
}
return true
}
/*
实现some()
*/
export function some (array, callback) {
for (let index = 0; index < array.length; index++) {
if (callback(array[index], index)) { // 只有一个结果为true, 直接返回true
return true
}
}
return false
}
2.3.测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数组声明式系列方法</title>
</head>
<body>
<script src="../dist/atguigu-utils.js"></script>
<script>
/*
需求:
1. 产生一个每个元素都比原来大10的新数组
2. 得到所有奇数的和
3. 得到值大于8且下标是偶数位的元素组成的数组
4. 找出一个值大于8且下标是偶数位的元素
5. 找出一个值大于8且下标是偶数位的元素的下标
6. 判断下标为偶数的元素是否都为奇数
7. 判断是否有下标为偶数的元素值为奇数
*/
const arr = [1, 3, 6, 9, 15, 19, 16]
/* 使用数组内置方法 */
// console.log(arr.map((item, index) => item + 10))
// console.log(arr.reduce((preTotal, item, index) => {
// return preTotal + (item%2===1 ? item : 0)
// }, 0))
// console.log(arr.filter((item, index) => item>8 && index%2===0))
// console.log(arr.find((item, index) => item>8 && index%2===0))
// console.log(arr.findIndex((item, index) => item>8 && index%2===0))
// console.log(arr.every((item, index) => index%2===1 || item%2===1))
// console.log(arr.some((item, index) => index%2===0 && item%2===1))
/* 使用自定义工具函数 */
console.log(aUtils.map(arr, (item, index) => item + 10))
console.log(aUtils.reduce(arr, (preTotal, item, index) => {
return preTotal + (item%2===1 ? item : 0)
}, 0))
console.log(aUtils.filter(arr, (item, index) => item>8 && index%2===0))
console.log(aUtils.find(arr, (item, index) => item>8 && index%2===0))
console.log(aUtils.findIndex(arr, (item, index) => item>8 && index%2===0))
console.log(aUtils.every(arr, (item, index) => index%2===1 || item%2===1))
console.log(aUtils.some(arr, (item, index) => index%2===0 && item%2===1))
</script>
</body>
</html>
3、数组去重
3.1.API 说明
- 根据当前数组产生一个去除重复元素后的新数组
- 如: [2, 3, 2, 7, 6, 7] ==> [2, 3, 7, 6]
3.2. 实现
-
方法1: 利用forEach()和indexOf()
- 说明: 本质是双重遍历, 效率差些
-
方法2: 利用forEach() + 对象容器
- 说明: 只需一重遍历, 效率高些
-
方法3: 利用ES6语法: from + Set 或者 ... + Set
- 说明: 编码简洁
3.3. 编码实现
unique.js
/*
方法1: 利用forEach()和indexOf()
说明: 本质是双重遍历, 效率差些
*/
export function unique1 (array) {
const arr = []
array.forEach(item => {
if (arr.indexOf(item)===-1) {
arr.push(item)
}
})
return arr
}
/*
方法2: 利用forEach() + 对象容器
说明: 只需一重遍历, 效率高些
*/
export function unique2 (array) {
const arr = []
const obj = {}
array.forEach(item => {
if (!obj.hasOwnProperty(item)) {
obj[item] = true
arr.push(item)
}
})
return arr
}
/*
方法3: 利用ES6语法
1). from + Set
2). ... + Set
说明: 编码简洁
*/
export function unique3 (array) {
// return Array.from(new Set(array))
return [...new Set(array)]
}
4、数组合并与切片
4.1. API 说明
4.2.编码实现
concat.js
: 自定义数组合并
/*
语法: var new_array = concat(old_array, value1[, value2[, ...[, valueN]]])
功能: 将n个数组或值与当前数组合并生成一个新数组
*/
export function concat (array, ...values) {
const arr = [...array]
values.forEach(value => {
if (Array.isArray(value)) {
arr.push(...value)
} else {
arr.push(value)
}
})
return arr
}
src/array/slice.js
: 自定义数组切片/* 语法: var new_array = slice(oldArr, [begin[, end]]) 功能: 返回一个由 begin 和 end 决定的原数组的浅拷贝, 原始数组不会被改变 */ export function slice (array, begin, end) { // 如果当前数组是[], 直接返回[] if (array.length === 0) { return [] } // 如果begin超过最大下标, 直接返回[] begin = begin || 0 if (begin >= array.length) { return [] } // 如果end不大于begin, 直接返回[] end = end || array.length if (end > array.length) { end = array.length } if (end <= begin) { return [] } // 取出下标在[begin, end)区间的元素, 并保存到最终的数组中 const arr = [] for (let index = begin; index < end; index++) { arr.push(array[index]) } return arr }
4.3 测试
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>数组合并与切片</title> </head> <body> <script src="../dist/atguigu-utils.js"></script> <script> console.log(aUtils.concat([1, 2], [3, 4], 6)) // [1, 2, 3, 4, 6] console.log(aUtils.slice([1, 3, 5, 7, 9])) // [1, 3, 5, 7, 9] console.log(aUtils.slice([1, 3, 5, 7, 9], 1, 3)) // [3, 5] console.log(aUtils.slice([1, 3, 5, 7, 9], 1, 10)) // [3, 5, 7, 9] </script> </body> </html>
5、数组扁平化
5.1 API 说明
- 语法: flatten(array)
- 取出嵌套数组(多维)中的所有元素放到一个新数组(一维)中
-
src/array/flatten.js
-
方法一: 递归 + reduce() + concat()
-
方法二: ... + some() + concat()
- 如: [1, [3, [2, 4]]] ==> [1, 3, 2, 4]
5.2 编码实现
/*
数组扁平化: 取出嵌套数组(多维)中的所有元素放到一个新数组(一维)中
如: [1, [3, [2, 4]]] ==> [1, 3, 2, 4]
*/
/*
方法一: 递归 + reduce() + concat()
*/
export function flatten1 (array) {
return array.reduce((pre, item) => {
if (Array.isArray(item) && item.some(cItem => Array.isArray(cItem))) {
return pre.concat(flatten1(item))
} else {
return pre.concat(item)
}
}, [])
}
/*
方法二: ... + some() + concat()
*/
export function flatten2 (array) {
let arr = [].concat(...array)
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr)
}
return arr
}
5.3 测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数组扁平化</title>
</head>
<body>
<script src="../dist/atguigu-utils.js"></script>
<script>
console.log(aUtils.flatten1([1, [3, [2, 4]]]))
console.log(aUtils.flatten2([1, [3, [2, 4]]]))
</script>
</body>
</html>
6.数组分块
6.1.API 说明
6.2.编码实现
/*
将数组拆分成多个 size 长度的区块,每个区块组成小数组,整体组成一个二维数组
*/
export function chunk (array, size) {
if (array.length===0) {
return []
}
size = size || 1
const bigArr = []
let smallArr = []
array.forEach(item => {
if (smallArr.length===0) {
bigArr.push(smallArr)
}
smallArr.push(item)
if (smallArr.length===size) {
smallArr = []
}
})
return bigArr
}
6.3.测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数组分块</title>
</head>
<body>
<script src="../dist/atguigu-utils.js"></script>
<script>
console.log(aUtils.chunk([1, 2, 3, 4, 5, 6, 7], 3)) // [[1,2,3], [4,5,6],[7]]
console.log(aUtils.chunk([1, 2, 3, 4, 5, 6, 7]))// [[1],[2],[3],[4],[5],[6],[7]]
console.log(aUtils.chunk([1, 2, 3, 4, 5, 6, 7], 8))// [[1, 2, 3, 4, 5, 6, 7]]
</script>
</body>
</html>
7.数组取差异
7.1.API 说明
7.2.编码实现
src/array/difference.js
/* difference(arr1, arr2): 得到arr1中所有不在arr2中的元素组成的数组(不改变原数组) 如: [1,3,5,7].difference([5, 8]) ==> [1, 3, 7] */ export function difference (arr1, arr2) { if (arr1.length===0) { return [] } else if (arr2.length===0) { return arr1.slice() } return arr1.filter(item => arr2.indexOf(item)===-1) }
7.3.测试
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>数组取差异</title> </head> <body> <script src="../dist/atguigu-utils.js"></script> <script> console.log(aUtils.difference([1,3,5,7], [5, 8])) </script> </body> </html>
8.删除数组中部分元素
8.1.API相关
8.2. 编码实现
/*
1. pull(array, ...values):
删除数组中与value相同的元素, 返回所有删除元素的数组
说明: 数组发生了改变
如: pull([1,3,5,3,7], 2, 7, 3, 7) ===> 数组变为[1, 5], 返回值为[3,3,7]
2. pullAll(array, values):
功能与pull一致, 只是参数变为数组
如: pullAll([1,3,5,3,7], [2, 7, 3, 7]) ===> 数组变为[1, 5], 返回值为[3,3,7]
*/
export function pull (array, ...values) {
if (array.length===0 || values.length===0) {
return []
}
var result = []
for (let index = 0; index < array.length; index++) {
const item = array[index]
if (values.indexOf(item)!==-1) {
array.splice(index, 1) //删除指定元素,index开始的位置,1表示删除一个
result.push(item)
index--
}
}
return result
}
export function pullAll (array, values) {
if (!values || !Array.isArray(values)) {
return []
}
return pull(array, ...values)
}
8.3.测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>删除数组中部分元素</title>
</head>
<body>
<script src="../dist/atguigu-utils.js"></script>
<script>
var arr = [1,3,5,3,7]
console.log(aUtils.pull(arr, 2, 7, 3, 7), arr)
var arr2 = [1,3,5,3,7]
console.log(aUtils.pullAll(arr2, [2, 7, 3, 7]), arr2)
</script>
</body>
</html>
9. 得到数组的部分元素
9.1.API 相关
9.2. 编码实现
/*
1. drop(array, count):
得到数组过滤掉左边count个后剩余元素组成的数组
说明: 不改变当前数组, count默认是1
如: drop([1,3,5,7], 2) ===> [5, 7]
2. dropRight(array, count):
得到数组过滤掉右边count个后剩余元素组成的数组
说明: 不改变数组, count默认是1
如: dropRight([1,3,5,7], 2) ===> [1, 3]
*/
export function drop (array, count=1) {
if (array.length === 0 || count >= array.length) {
return []
}
return array.filter((item, index) => index>=count)
}
export function dropRight (array, count=1) {
if (array.length === 0 || count >= array.length) {
return []
}
return array.filter((item, index) => index < array.length-count)
}
9.3.测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>得到数组的部分元素</title>
</head>
<body>
<script src="../dist/atguigu-utils.js"></script>
<script>
console.log(aUtils.drop([1,3,5,7], 2))
console.log(aUtils.drop([1,3,5,7], 4))
console.log(aUtils.drop([1,3,5,7]))
console.log(aUtils.dropRight([1,3,5,7], 2))
console.log(aUtils.dropRight([1,3,5,7], 4))
console.log(aUtils.dropRight([1,3,5,7]))
</script>
</body>
</html>