feat: 周报二期

add-license-1
xuwu 2021-06-06 11:25:37 +08:00
parent 885bd959ef
commit 668882c867
1 changed files with 15 additions and 1 deletions

View File

@ -11,4 +11,18 @@
- Node 12 岁生日了
- [.at() 进入 Stage 3](https://github.com/tc39/proposal-relative-indexing-method)
这是个挺不错的新语法。其他有些语言是可以用 `arr[-1]` 来获取数组末尾的元素,但是对于 JS 来说这是实现不了的事情。因为 `[key]` 对于对象来说就是在获取 `key` 对应的值。数组也是对象,对于数组使用 `arr[-1]` 就是在获取 `key``-1` 的值。由于以上原因,我们想获取末尾元素就得这样写 `arr[arr.length - 1]`,以后有了 `at` 这个方法,我们就可以通过 `arr.at(-1)` 来拿末尾的元素了,另外同样适用类数组、字符串。
这是个挺不错的新语法。其他有些语言是可以用 `arr[-1]` 来获取数组末尾的元素,但是对于 JS 来说这是实现不了的事情。因为 `[key]` 对于对象来说就是在获取 `key` 对应的值。数组也是对象,对于数组使用 `arr[-1]` 就是在获取 `key``-1` 的值。由于以上原因,我们想获取末尾元素就得这样写 `arr[arr.length - 1]`,以后有了 `at` 这个方法,我们就可以通过 `arr.at(-1)` 来拿末尾的元素了,另外同样适用类数组、字符串。
```js
// Polyfill
function at(n) {
// ToInteger() abstract op
n = Math.trunc(n) || 0;
// Allow negative indexing from the end
if(n < 0) n += this.length;
// OOB access is guaranteed to return undefined
if(n < 0 || n >= this.length) return undefined;
// Otherwise, this is just normal property access
return this[n];
}
```