嘿,有人可以告诉我如何在foreach循环中访问组件变量吗? 在这里我的 Plunker
public testVariable:number;
test(){
console.log('fired');
var x =[1,2,3,4];
x.forEach(function (e){
this.testVariable = e;
})
console.log( this.testVariable);
}
答案 0 :(得分:21)
如果您使用function (e)
,其中的this
将引用该函数的范围而不是类。
使用Arrow Function
(或Fat Arrow
)代替:
x.forEach((e) => {
this.testVariable = e;
})
当只有一个参数时,你也可以省略它周围的括号:
x.forEach(e => {
this.testVariable = e;
})
这是一篇很好的文章,解释了它的行为:https://basarat.gitbooks.io/typescript/docs/arrow-functions.html
答案 1 :(得分:4)
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
[request setHTTPMethod:@"GET"];
[request addValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"text/plain" forHTTPHeaderField:@"Accept"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSData * responseData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(@"requestReply: %@", jsonDict);
}] resume];
的值取决于您所在的范围。请考虑这样做:
this