gpt4 book ai didi

javascript - 如何将 NSArray 传递给 JavaScript 文件并在 JavaScript 中打印该数组?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:39:30 25 4
gpt4 key购买 nike

我正在寻找从 viewcontroller.m 文件发送一个 NSArray 到 data.js 文件但它不会在 JavaScript 中打印任何内容。以下是我的代码。

在我的viewdidload方法中

   - (void)webViewDidFinishLoad:(UIWebView*)theWebView
{
// Black base color for background matches the native apps
CDV=[[CDVViewController alloc]init];
news=[[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"latest news" ofType:@"plist"]];
NSArray *newsItems=[[NSArray alloc]init];
newsItems=[news valueForKey:@"News"];
NSData *jsonArray = [self arrayToJSON:newsItems];
NSString *jsonString = [[NSString alloc] initWithData:jsonArray
encoding:NSUTF8StringEncoding];
NSString *jsCall = [NSString stringWithFormat:@"yourJsFunction([%@])", jsonString];
[theWebView stringByEvaluatingJavaScriptFromString:jsCall];
NSLog(@"%@",jsonString);
// theWebView.backgroundColor = [UIColor blackColor];

return [super webViewDidFinishLoad:theWebView];
}


- (NSData *) arrayToJSON:(NSArray *) inputArray
{
NSError *error = nil;
id result = [NSJSONSerialization dataWithJSONObject:inputArray
options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}

在我的 one.js 文件中有这段代码:

function yourJsFunction(arr){
for(var i=0;i<arr.length;i++){
document.write(arr[i]);
}
return arr;
}

输出是:

ഡാറ്റാസെന്റർ:സത്യവാങ്മൂലംസമർപ്പിക്കാൻഅനുമതി‌,കാശ്മീർയുയു.

但我想要他们每个人分开而不是把“,”

当前输出:

enter image description here

新形象 enter image description here

最佳答案

js文件有一些变化
1.使用 toString() 将 arr 转换为正确的字符串2.拆分新字符串

var b=arr.toString().split(',');

现在打印 document.write(b[1]);它的工作!!!!!

在 .m 文件中就像“@Divaka”的选项

尝试在此处更改选项 NSJSONSerialization dataWithJSONObject:从 kNilOptions 到 NSJSONWritingPrettyPrinted

关于javascript - 如何将 NSArray 传递给 JavaScript 文件并在 JavaScript 中打印该数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19488284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com