规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.
ES2015中的箭头功能提供了更简洁的语法.我现在可以用箭头功能替换所有函数声明/表达式吗?我需要注意什么?
例子:
构造函数
function User(name) {
this.name = name;
}
// vs
const User = name => {
this.name = name;
};
Run Code Online (Sandbox Code Playgroud)
原型方法
User.prototype.getName = function() {
return this.name;
};
// vs
User.prototype.getName = () => this.name;
Run Code Online (Sandbox Code Playgroud)
对象(文字)方法
const obj = {
getName: function() {
// ...
}
};
// vs
const obj = {
getName: () => {
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
回调
setTimeout(function() {
// ...
}, 500);
// vs
setTimeout(() => {
// ...
}, …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种通过值而不是键来过滤地图的方法.我有一个在我的Angular应用程序中建模如下的数据集:
{
"85d55e6b-f4bf-47bb-a988-78fdb9650ef0": {
is_deleted: false,
public_email: "007@example.org",
id: "85d55e6b-f4bf-47bb-a988-78fdb9650ef0",
modified_at: "2017-09-26T15:35:06.853492Z",
social_url: "https://facebook.com/jamesbond007",
event_id: "213b01de-da9e-4d19-8e9c-c0dae63e019c",
visitor_id: "c3c232ff-1381-4776-a7f2-46c177ecde1c",
},
}
Run Code Online (Sandbox Code Playgroud)
这些条目上的键id与条目值上的字段相同.
给定其中几个条目,我想过滤并返回一个new Map()只包含给定条目的条目event_id.如果这是一个数组,我会做以下事情:
function example(eventId: string): Event[] {
return array.filter((item: Event) => item.event_id === eventId);
}
Run Code Online (Sandbox Code Playgroud)
本质上,我试图复制功能Array.prototype.map()- 只是在地图而不是数组.
我愿意使用Lodash,如果它能以更简洁的方式帮助实现这一点,因为它已经在我的项目中可用.
尝试在 Angular 中实现管道。在意识到 ngFor 不适用于地图之后。一些研究让我相信未来的功能将会解决这个问题,但与此同时,mapToIterable 管道就是答案。
我有以下代码:
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'mapToIterable'
})
export class MapToIterablePipe implements PipeTransform {
transform(map: Map<string, Object>, args: any = []): any {
const a: any[] = [];
console.log(map.keys()); // <- works as expected
for (const k in map) {
if (map.has(k)) {
console.log("hello"); // <- never executes
console.log(k);
a.push({key: k, val: map.get(k)});
}
}
console.log(a); // <- always empty
return a;
}
}
export const MAPTOITERABLE_PROVIDERS = [
MapToIterablePipe
];
Run Code Online (Sandbox Code Playgroud)
map.keys() …