让我的函数循环遍历数组

时间:2016-09-27 15:13:41

标签: javascript arrays loops

嘿,伙计们,所以我想做点什么,我不知道怎么做。我正在为我的兄弟会工作。我们有这个巨大的数组,里面有所有的bros信息。我想要一个循环遍历数组的函数。从第2列获取数据,然后将其写入页面。但是当它写入它时,它会添加一个链接。我的例子就是。这样它就可以将所有图像放在页面上。

我试图在控制台中运行它,但我不认为它是通过数组循环,我不知道我做错了什么。任何人都可以建议吗?

function imgTag(data) {
  var url = 'http://fratsite.com/images/'+data[1];
  return "<img src='"+url+"' width='392' height='400' alt='' />";
}

var output = document.write(imgTag);

console.log(output.join(''));
var foo = new Array();
foo[0] = ["Brother-0001","0001.jpg"];
foo[1] = ["Brother-0002","0002.jpg"];
foo[2] = ["Brother-0003","0003.jpg"];
foo[3] = ["Brother-0004","0004.jpg"];
foo[4] = ["Brother-0005","0005.jpg"];
foo[5] = ["Brother-0006","0006.jpg"];
foo[6] = ["Brother-0007","0007.jpg"];

3 个答案:

答案 0 :(得分:0)

更新了使用数组数组而不是对象数组的答案:

var imageForBro = function(bro){
   var name = bro.name,
       file = bro.image,
       path = 'http://fraternity.com/images/' + file;

   return "<img src='"+path+"' target='_blank'/>";
}

var bros = new Array();
bros[0] = ["Brother-0001","0001.jpg"];
bros[1] = ["Brother-0002","0002.jpg"];
bros[2] = ["Brother-0003","0003.jpg"];
bros[3] = ["Brother-0004","0004.jpg"];
bros[4] = ["Brother-0005","0005.jpg"];
bros[5] = ["Brother-0006","0006.jpg"];
bros[6] = ["Brother-0007","0007.jpg"];


for(var index in bros){
   var broData = bros[index],
       broName = broData[0],
       broImgFile = broData[1],
       imageEl = imageForBro(broImgFile);

   document.write(imageEl);  
}

如果你想将你的数组转换为一个更容易使用的对象数组......

var arrayOfBroObjects = [];
for(var index in bros){
    var broData = bros[index],
        brother = {
           name : broData[0],
           image: broData[1]
        };

    arrayOfBroObjects.push(brother);
}

现在它是一个对象数组!然后,您可以使用JSON对其进行编码/解码以供以后使用:

// encode the array in JSON notation as a string
broJson = JSON.stringify(arrayOfBroObjects);

// decode the JSON notation string into a JavaScrpt array
arrayOfBroObjects = JSON.parse(broJson);

此外,您可能希望使用jQuery之类的JavaScript库,这将使您在构建完整网站时更轻松。

答案 1 :(得分:0)

data.forEach(function(item) {
  var url = 'http://fratsite.com/images/'+item[1];
  document.write("<img src='"+url+"' width='392' height='400' alt='' />");
});

应该做你正在寻找的事情。

您的代码有什么问题?你没有在阵列上循环。您似乎只访问imgTag函数中的一个数组项,然后返回格式化的字符串。然后,当您尝试将output分配给document.write(imgTag)时,您已将其写入文档,并为output分配了返回值document.write(),这是{{1}}什么都没有。

我还建议使用JQuery。它会让你的生活更轻松。

答案 2 :(得分:0)

如果要在每个图像标记之间插入一些其他标记,则可以选择其他解决方案:

document.write(foo.map(function(data){
    var url = 'http://fratsite.com/images/'+data[1];
    return "<img src='"+url+"' width='392' height='400' alt='' />";
}).join('<br/>'));