【问题标题】:Convert this to javascript将此转换为 javascript
【发布时间】:2015-06-08 08:34:46
【问题描述】:

我有一些需要用 javascript 编写的 Swift 代码。我不知道该怎么做。 jsonresult 是 json 数据。有人可以帮忙吗?

let results: NSDictionary = jsonresult["results"] as! NSDictionary

let collection1: NSArray = results["collection1"] as! NSArray

for item in collection1 {

谢谢

【问题讨论】:

  • 到目前为止你尝试过什么?有没有自己研究过,比如怎么把json转成对象,或者怎么循环对象?
  • 是的,我有。我可以在 Swift 中做到这一点,但无法弄清楚如何在 JS 中做到这一点。我只需要知道这三行。 @ABakerSmith

标签: javascript json swift nsarray nsdictionary


【解决方案1】:

让结果:NSDictionary = jsonresult["results"] as! NSDictionary

var results = jsonresult["results"];

让 collection1: NSArray = results["collection1"] as! NSArray

var collection1 = results["collection1"];

对于collection1中的项目{

for(var item in collection1){

在 JS 项目中将索引。因此,要访问数组中的值,您需要访问数组的索引collection1[item]

如果jsonResult 是一个对象,您可以像这样简单地访问collection1

var jsonResult = {
   'results' : 
      { 'collection1': ["a", "b", "c", "d", "e"] }
};

var collection1 = jsonResult.results.collection1;

【讨论】:

  • 所以 var collection1 = jsonResult.results.collection1;可以替换JS中的三行吗?
  • 为了便于阅读,我将前两行替换为 var collection1 = jsonResult.results.collection。然后将在第三行使用 collection1(或更好的 var 名称)
猜你喜欢
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 2020-07-24
  • 2013-07-27
  • 2021-12-24
  • 2012-11-21
  • 1970-01-01
相关资源
最近更新 更多