# 放一些代码片段 **Repository Path**: wh3043/put-in-some-code-snippets ## Basic Information - **Project Name**: 放一些代码片段 - **Description**: 放一些 js 代码片段 - **Primary Language**: JavaScript - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-02-18 - **Last Updated**: 2021-03-31 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 放一些代码片段 #### 介绍 放一些 js 代码片段 ### 数组排序陷阱 ```javascript var arr = [0, 1, 5, 5, 10, 15] arr.sort() console.log(arr) // [0, 1, 10, 15, 5, 5] arr.sort((a, b) => a - b) console.log(arr) // [0, 1, 5, 5, 10, 15] ``` [类字段, this](https://www.bookstack.cn/read/zh.javascript.info/7a78297adc5a6c94.md) ```javascript class Button { constructor(value) { this.value = value; } click() { alert(this.value); } } let button = new Button("hello"); setTimeout(button.click, 1000); // undefined /* 这个问题被称为“丢失 this”。 我们在 函数绑定 一章中讲过,有两种可以修复它的方式: 传递一个包装函数,例如 setTimeout(() => button.click(), 1000)。 将方法绑定到对象,例如在 constructor 中: */ class Button { constructor(value) { this.value = value; this.click = this.click.bind(this); } click() { alert(this.value); } } let button = new Button("hello"); setTimeout(button.click, 1000); // hello /* 类字段为后一种解决方案提供了更优雅的语法: */ class Button { constructor(value) { this.value = value; } click = () => { alert(this.value); } } let button = new Button("hello"); setTimeout(button.click, 1000); // hello /* 类字段 click = () => {...} 在每个 Button 对象上创建一个独立的函数,并将 this 绑定到该对象上。 然后,我们可以将 button.click 传递到任何地方,并且它会被以正确的 this 进行调用。 这在浏览器环境中,当我们需要将一个方法设置为事件监听器时尤其有用。 */ ``` ```javascript // 2021年02月18日23:30:18 剥洋葱 function lookup(dataObj, keyName) { // console.log(dataObj, keyName); let keys = keyName.split(".") let temp = dataObj for (let x of keys) { temp = temp[x] } return temp } let res = lookup({ a: { b: { c: 100 } }, x: 90 }, 'a.b.c') console.log('res:', res) // 100 ```