ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 1. 事件监听函数 ~~~ /** * @params eventName 方法名称:有 "click", "resize", "mouseover"... * @params event 方法 function() {} * @params 事件类型为冒泡或捕获,默认false冒泡传递 */ // 添加监听事件 window.addEventListener(eventName, event, false); // 移除监听事件 window.removeEventListener(eventName, event, false); ~~~ ## 2. 操作数组的方法 ~~~ const array = [2, 1, 4, 3]; // 数组排序 array.sort(function(a, b) { return a >= b }) // [1, 2, 3, 4] ~~~ // 数组更改 | 方法 | 参数值 | 作用效果 | | --- | --- | --- | | push | item | 向后添加 | | pop | item| 从后删除 | | unshift | item | 向前添加 | | shift | item | 从前删除 | | slice | startIndex, endIndex | 删除数组,返回被删除部分, 不更改原数组 | | splice | startIndex, endIndex | 删除数组,返回被删除部分, 会更改原数组 | ## 3. 判断数据类型 ### typeof() // 只能判断基本类型 ~~~ typeof(false) // " typeof(null) // "object" typeof(Array) // "object" typeof(Object) // "object" ~~~ ### instanceof // 判断是否为某个所需的数据类型 ~~~ arr instanceof Array // true ~~~ ### Object.prototype.toString.call() // 判断是否为某个所需的数据类型 ~~~ // Object.prototype.toString() 数据原型类型,call() 更改 this 指向 Object.prototype.toString.call(arr) === "[object Array]" // true ~~~ ### constructor // 判断是否为某个所需的数据类型 ~~~ arr.constructor === Array // true ~~~ ## 4. 递归调用 > 在处理一些复杂型数据时常用 ~~~ // 树型数据的处理 const treeData = [ { name: "1", children: [ { name: "1-1" } ] } ] deepFor(treeData) { const arr = []; treeData.forEach(ele => { const temp = { name: ele.name, key: 0 }; if (ele.children && ele.children.length > 0) { temp.children = deepFor(ele.children); } arr.push(temp); }); return arr; } ~~~