【问题标题】:javascript for loop not iterating completely through objectjavascript for循环没有完全遍历对象
【发布时间】:2017-09-06 23:25:15
【问题描述】:

我目前正在尝试通过使用 For 循环对其进行迭代,将数据从 JS 对象动态加载到 html 容器中。

我撞到的墙似乎是因为 For 循环不会遍历整个对象,即使我根据计算的 For 循环中保存的对象数量设置了高阈值JS 对象。

一个可行的解决方案会将所有对象加载到它们各自的 html 容器中。在这一点上,我不关心在成就属性对象中显示对象。

这个实验是为了更好地理解纯Javascript,所以请不要对Jquery或框架提出建议。

数据对象:

var data = { projects: [{
  title: "GET BORN",
  tags: ["Live Events", "Stage Design", "Event Promotion", "Music"],
  date_started: "21/09/12",
  date_finished: "Finish Date",
  description: "Music events that explores the underground sound",
  achievements: [{milestone:"Launched Brand", date:"datetime",  details:"blah"}, {milestone:"Hosted First Night", date:"datetime",  details:"moreblah"}, {milestone:"Sold Out Lakota +1000 People",   date:"datetime", details:"moreblah"}],
  position: 1  
}, {
  title: "FAIRSTREAM",
  tags: ["Web Application", "Trademark", "Music streaming"],
  date_started: "10/05/16",
  date_finished: "Finish date",
  description: "Equal opportunity music streaming application",
  achievements: [{milestone:"Launched Brand", date:"datetime", details:"blah"}],
  position: 2
}]}

视图生成函数:

const buildProjectView = (dataSet) => {
  const currentProjectIndex = 0
  let dataLen = Object.keys(dataSet.projects[currentProjectIndex]).length
  // console.log(dataLen)

  let objKey = Object.keys(dataSet.projects[currentProjectIndex])
  let objValue = Object.values(dataSet.projects[currentProjectIndex])
  // console.log(objValue)

  for (let i = 0; i < dataLen; i++) {
    // console.log("count: " + i)
    console.log(objKey[i] + ": " + objValue[i])

    let theTitle = document.getElementById(objKey[i])
    let content = document.createTextNode(objValue[i])
    theTitle.appendChild(content)
  }
}

window.onload = buildProjectView(data)

HTML 样板:

<html>
<head>
  <title>Mysite Playground</title>
</head>
<body>
  <div class="container">
    <section class="head">
      <h1 id="title"/>
      <h2 id="description"/>
      <h3 id="date_started"/>
    </section>
    <section class="body">
      <p id="position">#</p>
      <p id="achievements"/>
      <p id="tags"/>
    </section>
  </div>
</body>
</html>

我的编码测试平台,带有示例和一些基本样式: https://codepen.io/wntwrk/pen/bqXYMO

提前感谢您的帮助。

【问题讨论】:

  • const currentProjectIndex = 0 let dataLen = Object.keys(dataSet.projects[currentProjectIndex]).length - 这只是处理带有title: "GET BORN", 的对象,并且总是返回7。

标签: javascript html for-loop iteration javascript-objects


【解决方案1】:

这应该为您提供一个起点,让您可以使用一些东西。

你有一个包含数组的数组和一个对象数组。

请注意,简单地将内容“推入”现有标记/样板的 DOM 对您没有帮助,您需要克隆它以允许更多实例 - 这就是我所做的。

使用提供的这些数据:

/*jshint esversion: 6 */
var data = {
  projects: [{
    title: "GET BORN",
    tags: ["Live Events", "Stage Design", "Event Promotion", "Music"],
    date_started: "21/09/12",
    date_finished: "Finish Date",
    description: "Music events that explores the underground sound",
    achievements: [{
      milestone: "Launched Brand",
      date: "datetime",
      details: "blah"
    }, {
      milestone: "Hosted First Night",
      date: "datetime",
      details: "moreblah"
    }, {
      milestone: "Sold Out Lakota +1000 People",
      date: "datetime",
      details: "moreblah"
    }],
    position: 1
  }, {
    title: "FAIRSTREAM",
    tags: ["Web Application", "Trademark", "Music streaming"],
    date_started: "10/05/16",
    date_finished: "Finish date",
    description: "Equal opportunity music streaming application",
    achievements: [{
      milestone: "Launched Brand",
      date: "datetime",
      details: "blah"
    }],
    position: 2
  }]
};

我添加了一些功能,希望它更容易理解。

// convert the "boilerplate" to a class based avoiding duplicate id's
function idToClass(node) {
  var child, nodes = node.childNodes;
  for (var i = 0, len = nodes.length; i < len; i++) {
    child = nodes[i];
    if (typeof child.id === 'string' && child.id !== "") {
      child.className = child.id;
      child.removeAttribute("id");;
    }
    if (child.childNodes && child.childNodes.length) {
      idToClass(child);
    }
  }
}

let addItem = (project, aclone, name) => {
  let el = aclone.getElementsByClassName(name);
  if (el.length && typeof project[name] !== "object") {
    el[0].textContent = project[name];
  }
  if (el.length && typeof project[name] === "object") {
    /// do something with objects like the "achievements"
  }
};

let addProject = (project, aclone) => {
  var k = Object.keys(project);
  k.forEach(function(item) {
    addItem(project, aclone, item);
  });
  return aclone;
};

const buildProjectView = (dataSet) => {
  let y = document.getElementsByClassName('container');
  //clone and change ids to classes
  let aclone = y[0].cloneNode(true);
  idToClass(aclone);
  for (let i = 0; i < dataSet.projects.length; i++) {
    let n = addProject(dataSet.projects[i], aclone.cloneNode(true));
    y[0].parentNode.appendChild(n, aclone);
  }
  // COULD remove the boilerplate here:
  // y[0].removeNode();
};

window.onload = buildProjectView(data);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 2014-07-14
    • 2013-03-09
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    相关资源
    最近更新 更多