[英]Transform keys to values, values to keys in json object using typescript
[英]Accessing keys and values of an object using forEach in TypeScript
为什么在案例 1 中抛出错误,但在案例 2 中没有?
情况1:
export class AppComponent implements OnInit{
obj={
name:"XYZ",
age:"22",
height:"5"
}
ngOnInit() {
this.calling();
}
calling(){
if(true){
Object.keys(this.obj).forEach(function(key)
{
console.log(key,this.obj[key])
}
)
}
}
}
错误:无法读取未定义的属性“obj”
案例2:
export class AppComponent implements OnInit{
ngOnInit() {
this.calling();
}
calling() {
if(true){
let obj={
name:"XYZ",
age:"22",
height:"5"
}
Object.keys(obj).forEach(function(key)
{
console.log(key,obj[key])
}
)
}
}
}
在这种情况下,控制台中不会显示任何错误。
当您使用function()
定义 function 时, this
引用的值会发生变化。 this
您想继续参考 class,请使用箭头 function。
export class AppComponent implements OnInit {
obj = {
name:"XYZ",
age:"22",
height:"5"
}
ngOnInit() {
this.calling();
}
calling(){
if(true){
Object.keys(this.obj).forEach((key) =>
{
console.log(key, this.obj[key])
}
)
}
}
}
您还可以通过在 function 上调用bind()
来解决this
问题,以便在 function 中进行设置。
export class AppComponent implements OnInit {
obj = {
name:"XYZ",
age:"22",
height:"5"
}
ngOnInit() {
this.calling();
}
calling(){
if(true){
const func = function(key) {
console.log(key, this.obj[key])
};
Object.keys(this.obj).forEach(func.bind(this));
}
}
}
你没有掌握 Javascript 中的 scope。
在您的第一个示例中,您的回调 function 有自己的this
定义,因此外部函数this
不可访问。
要解决这个问题,您可以使用箭头 function (或者您可以使用.bind(this)
但我从未真正使用过)。
//arrow functinon
Object.keys(this.obj).forEach((key) => {
console.log(key,this.obj[key])
)}
这里有更多关于箭头函数与绑定的阅读: https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/
您的第二个示例有效,因为您使用let
定义了obj
,因此它可以在 function 中访问。
这是一篇关于 var/let/const https://www.deadcoderising.com/2017-04-11-es6-var-let-and-const-the-battle-between-function-scope-and-block-的好文章范围/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.