【发布时间】:2015-11-05 19:57:07
【问题描述】:
也许我只是累了,但经过非常努力后,我似乎无法为我遇到的这个问题想出一个解决方法。
我正在使用 Tumblr 的 API 访问特定的博客,并从博客中获取一些帖子。博客上的所有帖子都有标题、图片和网站链接。在我的代码中,我从 API 迭代 JSON 并将每个标题存储在标题数组中,将每个图像的链接存储在图像数组中,并将每个网站链接存储在链接数组中。我打算像这样使用这些数组:title[1]、image[1]、links[1],所以到最后,所有的帖子都会在他们自己的图片和链接旁边。
标题和链接数组完美运行。但是,图像数组没有。问题是来自 Tumblr 博客的一些帖子有 2-3 张照片,而不是 1 张。这意味着在我的图像数组中插入了 2-3 个图像链接以用于某些帖子。所以最后,我的三个数组的长度是: 标题:91,链接:91,图像:120。这是一个问题,因为例如第一篇文章在图像数组中插入了 2 张图像。这意味着第一篇文章中的图片将与第二篇文章中的标题和链接分组。
有什么方法可以让代码只获取第一张图片?我阅读了文档,但找不到任何东西。
代码:
$(data.response.posts).each(function(index, value){
if(value.type === "photo"){
try{
var newLink = value.source_url;
var newTitle = value.slug;
if(checkIfNotExists(newLink, links) && checkIfNotExists(newTitle, titles)){
links.push(newLink);
titles.push(newTitle);
}
$(value.photos).each(function(idx, val){
var newImage = val.original_size.url;
if(checkIfNotExists(newImage, images)){
images.push(newImage);
}
});
}catch(err){
console.log("err");
}
}
//Function to ensure no duplicate
function checkIfNotExists(checkValue, fullArray){
if(!fullArray.indexOf(checkValue)>-1 && checkValue!=='undefined' && checkValue!==undefined && checkValue!=='default'){
return true;
}else{
return false;
}
}
如果有人能提供任何帮助,我将不胜感激。
【问题讨论】:
标签: javascript arrays json jsonp tumblr