【问题标题】:javascript: empty array valuejavascript:空数组值
【发布时间】:2021-12-23 00:04:32
【问题描述】:

我有以下循环调用 api 并将数据推送到数组,问题是 API 返回某些属性的空值,即 "primaryTag": null 并且正在破坏我的代码,我该如何处理它以放置如果任何值为空,则为静态值?

for (var a in audience) {
        
      var aId = audience[a];
      var url = base+'?'+query+'&AudienceId='+aId
      var req = new HttpClientRequest(url);
      req.header["Content-Type"] = "application/json"
      req.method = "GET"
      req.execute();
      var resp = req.response;  
       
      if( resp.code != 200 )
      throw "HTTP request failed with " + resp.message
         
      var posts = JSON.parse(resp.body)
      logInfo(resp.code+' '+url);

      
        for (i = 0; i < 11; i++) {
          articlesList_json.push({
                "title":posts[i].title, 
                "pubDate":posts[i].publishedDate, 
                "link":posts[i].url, 
                "imageURL":posts[i].imageUrl, 
                "description": posts[i].description,
                "category": posts[i].category.name,
                "audience": posts[i].audience.name+'-'+posts[i].audience.id,
                "tag": posts[i].primaryTag.name,
                "episerverId":posts[i].episerverId,
            });
        } 
      
}//for loop end

【问题讨论】:

  • HttpClientRequest 是库的一部分吗?那是从哪里来的?当我用谷歌搜索它时,我得到了 Adob​​e 链接。这是 Adob​​e 框架的一部分吗?
  • 感谢零,确实是adobe活动功能

标签: javascript arrays xml api


【解决方案1】:

看看optional chaining

"tag": posts[i].primaryTag?.name ?? "N/A"

或者使用三元:

"tag": posts[i].primaryTag ? posts[i].primaryTag.name : "N/A"

【讨论】:

  • 谢谢我会研究这个话题!
  • @DavidGarcia 我也添加了适当的三元测试
【解决方案2】:

诸如 null、未定义、空字符串、0 和 NaN 之类的值在 Javascript 中被评估为 false。

您可以使用 if 条件检查值是否不为空

if(value) {
// value is not null
// do something with the value
}

在您的示例中,您可以使用三元表达式来检查它

        for (i = 0; i < 11; i++) {
          articlesList_json.push({
                // check if value is not falsy and provide a default when it is
                "title":posts[i].title ? posts[i].title : "no value",
                // ...
            });
        } 

查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator了解更多信息

【讨论】:

  • 感谢这两个解决方案的工作。
猜你喜欢
  • 2016-08-06
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
相关资源
最近更新 更多