【问题标题】:Limit the number of objects retrieved while parsing JSON details限制解析 JSON 详细信息时检索的对象数量
【发布时间】:2014-01-28 20:43:38
【问题描述】:

以下是我用 JavaScript 解析的部分 JSON 数据。

  "credits":{
"cast":[{
    "id":819,"name":"Edward Norton","character":"The Narrator","order":0,"cast_id":4,"profile_path":"/iUiePUAQKN4GY6jorH9m23cbVli.jpg"
    },



  {"id":287,"name":"Brad Pitt","character":"Tyler Durden","order":1,"cast_id":5,"profile_path":"/kc3M04QQAuZ9woUvH3Ju5T7ZqG5.jpg"
    },

    {"id":1283,"name":"Helena Bonham Carter","character":"Marla Singer","order":2,"cast_id":6,"profile_path":"/58oJPFG1wefMC0Vj7sFzHPrm67J.jpg"
    },

    {"id":7470,"name":"Meat Loaf","character":"Robert 'Bob' Paulson","order":3,"cast_id":7,"profile_path":"/pwNyXgegO1nlZ8uWT847JM8EjGj.jpg"
    },

    {"id":7499,"name":"Jared Leto","character":"Angel Face","order":4,"cast_id":30,"profile_path":"/msugySeTCyCmlRWtyB6sMixTQYY.jpg"
    },

    {"id":7471,"name":"Zach Grenier","character":"Richard Chesler","order":5,"cast_id":31,"profile_path":"/jghYiKdNkVehKpiVyE97AWrU9KQ.jpg"
    },

    {"id":7497,"name":"Holt McCallany","character":"The Mechanic","order":6,"cast_id":32,"profile_path":"/hQBfcw9KVszdenlTZTR8AIrSpex.jpg"
    },

    {"id":7498,"name":"Eion Bailey","character":"Ricky","order":7,"cast_id":33,"profile_path":"/4MnRgrwuiJvHsfoiJrIUL4TkfoC.jpg"}]

我用下面的代码解析数据,它工作得很好。我的问题是我想限制提取的演员数量,例如只有 5 个。

actor = 0,
acting = [];

for (actor = 0; actor < entries.credits.cast.length; actor++) {
    acting.push(entries.credits.cast[actor].name + ' as ' 
                 + entries.credits.cast[actor].character);
}

document.getElementById('cast').innerHTML = acting.join(', ');

【问题讨论】:

  • for (actor = 0; actor &lt; entries.credits.cast.length; actor++) { 更改为for (actor = 0; actor &lt; 5; actor++) { 将从列表中拉出前五个。
  • @RyanWillis 但是当少于 5 个时会出现错误,所以 min(5, entries.credits.cast.length) 会比 5 更好
  • 我的错,那么在acting = []; 之后你可以拥有actlimit = (entries.credits.cast.length &lt; 5) ? entries.credits.cast.length: 5; 并将5 更改为actlimit
  • @RyanWillis 谢谢!
  • @LoganMurphy 感谢您指出这一点

标签: javascript jquery json parsing themoviedb-api


【解决方案1】:

你可以这样做:

var acting = [];
var maxCount = 5;
var count = entries.credits.cast.length;
if(count > maxCount) count = maxCount;
for (var actor = 0; actor < count; actor++) {
    acting.push(entries.credits.cast[actor].name + ' as ' + entries.credits.cast[actor].character);
}

document.getElementById('cast').innerHTML = acting.join(', ');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    相关资源
    最近更新 更多