[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;
}
~~~