代码改变世界

利用JavaScriptCore实现简单的功能(阶乘)

2015-07-16 10:05  甘雨路  阅读(155)  评论(0编辑  收藏  举报
 1 #import "RootViewController.h"
 2 #import <JavaScriptCore/JavaScriptCore.h>
 3 
 4 @interface RootViewController ()
 5 @end
 6 
 7 @implementation RootViewController
 8 
 9 - (void)viewDidLoad {
10     [super viewDidLoad];
11     
12     JSContext *context = [[JSContext alloc] init];
13     context[@"factorial"] = ^(int x){
14         int factorial = 1;
15         for (; x > 1; x--) {
16             factorial *= x;
17         }
18         return factorial;
19     };
20     [context evaluateScript:@"var fiveFactorial = factorial(5);"];
21     JSValue *fiveFactorial = context[@"fiveFactorial"];
22     NSLog(@"5! = %@",fiveFactorial);
23     
24 }
25 
26 @end