【问题标题】:Javascript Loop (Beginner) [closed]Javascript循环(初学者)[关闭]
【发布时间】:2016-12-09 21:43:50
【问题描述】:

我目前正处于学习 Javascript 的初级阶段,想知道你如何能够遍历这个数组并将所有数据输出为 html 内容:

var links = new Array(); //Missing this part as code

links[0] = new Array();
links[0]["linkName"] = "W3Schools";
links[0]["linkLogo"] = "http://www.w3schools.com/images/w3schools.png";
links[0]["linkURL"] = "http://www.w3schools.com/";
links[0]["linkDescription"] = "W3Schools is a web developer information website, with tutorials and references relating to web development topics such as HTML, CSS, JavaScript and PHP.";

links[1] = new Array();
links[1]["linkName"] = "Code Academy";
links[1]["linkLogo"] = "";
links[1]["linkURL"] = "https://www.codecademy.com/";
links[1]["linkDescription"] = "Codecademy is an online interactive platform that offers free coding classes in 9 different programming languages.";

links[2] = new Array();
links[2]["linkName"] = "";
links[2]["linkLogo"] = "http://www.w3.org/2008/site/images/logo-w3c-mobile-lg";
links[2]["linkURL"] = "http://www.w3.org/";
links[2]["linkDescription"] = "The World Wide Web Consortium is the main international standards organization for the World Wide Web.";

【问题讨论】:

  • “将所有数据输出为html内容”真的很模糊。此外,在提出 SO 问题之前,请尝试使用谷歌搜索并展示您尝试过的内容。人们很乐意为您提供帮助。
  • 这是一个相当奇怪的数据结构,让每个数组项包含一个具有属性的对象不是更容易吗? (我不确定links[0]["linkName"] = "W3Schools"; 会按照你的想法做)
  • 反对你的人是迂腐的白痴,他们对你没有定义“html”和“输出”感到不安。代表他们接受我的道歉。 SO上的大多数人都很棒,整个社区也是如此!给 .forEach 一个 google,JS 中的循环,也许还有一般的 JS 教程!你可能已经深入到了最深处,所以慢慢来,继续编码:) 一切顺利!
  • 感谢斯坦的客气话! :) 我很感激!

标签: javascript arrays loops if-statement


【解决方案1】:

使用您的结构,我们可以做到这一点:

var links = new Array(); // Missing this part as code

links[0] = new Array();
links[0]["linkName"] = "W3Schools";
links[0]["linkLogo"] = "http://www.w3schools.com/images/w3schools.png";
links[0]["linkURL"] = "http://www.w3schools.com/";
links[0]["linkDescription"] = "W3Schools is a web developer information website, with tutorials and references relating to web development topics such as HTML, CSS, JavaScript and PHP.";

links[1] = new Array();
links[1]["linkName"] = "Code Academy";
links[1]["linkLogo"] = "http://2.bp.blogspot.com/-5_nn_mBDGb0/U3RBFBDiozI/AAAAAAAAm60/kOmwt-F5x8g/s1600/codeacademy.png";
links[1]["linkURL"] = "https://www.codecademy.com/";
links[1]["linkDescription"] = "Codecademy is an online interactive platform that offers free coding classes in 9 different programming languages.";

links[2] = new Array();
links[2]["linkName"] = "The World Wide Web Consortium";
links[2]["linkLogo"] = "http://www.w3.org/2008/site/images/logo-w3c-mobile-lg";
links[2]["linkURL"] = "http://www.w3.org/";
links[2]["linkDescription"] = "The World Wide Web Consortium is the main international standards organization for the World Wide Web.";

// Loop through the main array
for(var i = 0; i < links.length; ++i){

  // As we loop, we'll create new HTML elements that will be configured
  // with the information we extract from the objects in the array:
  var div = document.createElement("div");
  var a = document.createElement("a");
  var img = document.createElement("img");
  
  // Use data in the nested array to configure the new HTML element
  a.href = links[i]["linkURL"];
  img.src = links[i]["linkLogo"];
  img.alt = links[i]["linkDescription"];
  img.title = links[i]["linkName"];
  
  // Place the image inside of the link:
  a.appendChild(img);
  
  // Place the link inside of the div
  div.appendChild(a);
  
  // Inject div element into the web page
  document.body.appendChild(div);
}
img {width:200px}

然而,在 JavaScript 中,数组最适合存储单个数据项,甚至是嵌套数组。 但是,当您需要存储名称和值以配合这些名称时,最好使用 Object,它专为键/值对存储而设计。

这是您的数据,重新组织成对象,然后放入数组中,最后循环数组,提取对象数据并将数据放入 HTML 元素中。

// First set up objects to store the name/value pairs (arrays don't do this)
var object1 = {
 linkName : "W3Schools",
 linkLogo : "http://www.w3schools.com/images/w3schools.png",
 linkURL : "http://www.w3schools.com/",
 linkDescription : "W3Schools is a web developer information website, with tutorials and references relating to web development topics such as HTML, CSS, JavaScript and PHP."
};

var object2 = {
 linkName : "Code Academy",
 linkLogo : "http://2.bp.blogspot.com/-5_nn_mBDGb0/U3RBFBDiozI/AAAAAAAAm60/kOmwt-F5x8g/s1600/codeacademy.png",
 linkURL : "https://www.codecademy.com/",
 linkDescription : "Codecademy is an online interactive platform that offers free coding classes in 9 different programming languages."
};

var object3 = {
 linkName : "The World Wide Web Consortium",
 linkLogo : "http://www.w3.org/2008/site/images/logo-w3c-mobile-lg",
 linkURL : "http://www.w3.org/",
 linkDescription : "The World Wide Web Consortium is the main international standards organization for the World Wide Web."
};

// Place the objects into an array:
var objects = [object1, object2, object3];

// Loop through each of the objects in the array
for(var i = 0; i < objects.length; ++i){

  // As we loop, we'll create new HTML elements that will be configured
  // with the information we extract from the objects in the array:
  var div = document.createElement("div");
  var a = document.createElement("a");
  var img = document.createElement("img");
  
  // Use data in the object to configure the new HTML element
  a.href = objects[i].linkURL;
  img.src = objects[i].linkLogo;
  img.alt = objects[i].linkDescription;
  img.title = objects[i].linkName;
  
  // Place the image inside of the link:
  a.appendChild(img);
  
  // Place the link inside of the div
  div.appendChild(a);
  
  // Inject div element into the web page
  document.body.appendChild(div);
}
img {width: 200px;}

【讨论】:

  • 我觉得闹鬼:)
  • @Lain 为什么会这样?
  • 一天多次看到同一个名字有点不寻常,至少对我来说:)
  • @Lain 啊,哈哈!我什至没有注意到。我几乎每天都在。
【解决方案2】:

以下代码将给定结构映射到表示包含所有给定元素的 html 的字符串数组:

const linksAsHTML = links.map(link=>
`<a href="${link["linkURL"]}" title="${links["linkDescription"]}">
  <img src="${link["linkLogo"]}" alt="${links["linkName"] }"/>
</a>`);

有很多方法可以将这个字符串数组转换为页面上的 html,但作为初学者,我建议学习如何使用 jQuery

注意:这只是无数种方法中的一种,但希望这可以帮助您准确地确定您想要做什么。

【讨论】:

  • 我建议初学者远离 JQuery,因为事实证明他们总是误用和过度使用它而没有学习 JavaScript 的基础知识。
  • @ScottMarcus,我相信我理解你的担忧——我本可以写一些关于使用“document.createElement”和跨浏览器特性等的东西,但是,咳咳,“不是没有人有时间这样做”。 jQuery 确实通过隐藏不必要的复杂性让一些事情变得更容易,这可能是一把双刃剑,但你不应该假设有人会滥用它。此外,对于某些人来说,在不了解 JS 其余部分的情况下学习 jQuery 对他们的目的来说是很好的,因此没有理由强迫他们在不必要的情况下学习该语言的所有部分。
  • 作为一个 25 多年以来一直在教 JavaScript(以及许多其他编程语言)的人,我可以肯定地说,如果没有很好地学习 JavaScript,就使用 JQuery,它总是会导致灾难。尤其是因为 DOM 现在有许多 API 用于最初吸引开发人员使用 JQuery 的许多事物。我无法告诉您我看到 JQuery 库包含在代码中的频率,这些代码仅执行简单的事件绑定或查询。
  • @ScottMarcus 点。你会如何改进我的答案?
  • 只要目标受众拥有符合 ES6 标准的浏览器,您的答案就很好。我只是在评论您的 JQuery 评论,而不是您的答案。
【解决方案3】:

数据结构有点不确定,所以我认为这些是锚点:

links = []; //A man missed a declaration

links[0] = new Array();
links[0]["linkName"] = "W3Schools";
links[0]["linkLogo"] = "http://www.w3schools.com/images/w3schools.png";
links[0]["linkURL"] = "http://www.w3schools.com/";
links[0]["linkDescription"] = "W3Schools is a web developer information website, with tutorials and references relating to web development topics such as HTML, CSS, JavaScript and PHP.";

links[1] = new Array();
links[1]["linkName"] = "Code Academy";
links[1]["linkLogo"] = "";
links[1]["linkURL"] = "https://www.codecademy.com/";
links[1]["linkDescription"] = "Codecademy is an online interactive platform that offers free coding classes in 9 different programming languages.";

links[2] = new Array();
links[2]["linkName"] = "";
links[2]["linkLogo"] = "http://www.w3.org/2008/site/images/logo-w3c-mobile-lg";
links[2]["linkURL"] = "http://www.w3.org/";
links[2]["linkDescription"] = "The World Wide Web Consortium is the main international standards organization for the World Wide Web.";

//Looping though the array
for(var i=0, j=links.length; i<j; i++){
    if (!!links[i]['linkName']){ //Displaying empty links makes less sense
        //Creating a new anchor
        var tA = document.body.appendChild(document.createElement('a'));
        tA.href = links[i]['linkURL']; //Assigning the href
        tA.innerHTML = links[i]['linkName']; //Assigning the name
        tA.title = links[i]['linkDescription'];  //Assigning the description

    //Adding logo if available
    if(!!links[i]['linkLogo']){
        var tI = tA.appendChild(document.createElement('img'));
        tI.src = links[i]['linkLogo']
    }
    }
}

【讨论】:

  • 我需要输出所有这些数据并将其格式化为 HTML,您的代码没有这样做,还有其他想法吗?
  • @JuliaM:恐怕我不理解那个评论。
【解决方案4】:
 for (var i = 0, len = arr.length; i < len; i++) {
   someFn(arr[i]);
 }

【讨论】:

  • 请使用edit链接解释这段代码是如何工作的,不要只给出代码,因为解释更有可能帮助未来的读者。