javascript for循环不能完全遍历对象

时间:2017-04-11 14:02:09

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

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

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

工作解决方案将所有对象加载到各自的html容器中。在这一点上,我并不担心在achievement属性对象中显示对象。

这个实验是为了更好地理解Pure 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 Boilerplate:

<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

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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

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

请注意,简单地将内容“推送”到现有标记/样板上的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);