构建Javascript对象 - 我遇到了属性类型的问题。
import { Component } from '@angular/core';
import { Router, NavigationEnd, ActivatedRouteSnapshot } from '@angular/router';
import { TitleService } from './shared/title.service';
@Component({
selector: 'ctm-app',
template: `
<!--<a [routerLink]="['/dashboard']">Dashboard</a>
<a [routerLink]="['/login']">Login</a>
<a [routerLink]="['/']">Rooting</a>-->
<router-outlet></router-outlet>
`
})
export class AppComponent {
constructor(private router: Router, private titleService: TitleService) {
this.router.events.filter((event) => event instanceof NavigationEnd).subscribe((event) => {
console.log("AppComponent.constructor: Setting HTML document's Title");
this.titleService.CTMGenerateTitle(this.router.routerState.snapshot.root);
});
}
}
控制台显示==&gt;对象{Alice:2,Bob:1,Tiff:1,Bruce:1}
我试着去==&gt;对象{&#39; Alice&#39;:2,&#39; Bob&#39;:1,&#39; Tiff&#39;:1,&#39; Bruce&#39;:1}
https://jsfiddle.net/0j74kbky/
编辑1
我在这里找到了这个样本: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=example
也许我真正的问题是使用此属性来显示
==&GT;爱丽丝存在2次
编辑2
所以我的愚蠢解决方案是:
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
console.log(countedNames);
感谢所有人!
答案 0 :(得分:0)
控制台以这种方式显示它,但Alice,Bob,Tiff和Bruce都已经是字符串了。
如果您拿到钥匙并对其进行打字,您会看到:
Object.keys(countedNames).forEach(function(name) {
console.log(typeof name);
});
在此处查看: