JavaScript For循环跳过数组中的项
JavaScript For Loop Skipping items in an Array
我对这里发生的事情有点困惑。我有一个html无序列表,我是根据属性值把它整理成3个单独的列表。这是非常基本的,我知道,但我遇到了一些特殊的for循环和它的增量。
[this is code provided to be worked with]
<ul id="queue">
<li want="coffee">Phil(html)</li>
<li want="coffee">Sandy(html)</li>
<li want="sandwich">Enrique(html)</li>
<li want="coffee">Joe(html)</li>
<li want="muffin">Alex(html)</li>
<li want="chili">Zoe(html)</li>
<li want="sandwich">Bahamut(html)</li>
<li want="timbits">Rydia(html)</li>
</ul>
然后整理成这些列表
[this is code provided to be worked with]
<section id="sandwiches">
<h1>Sandwich line</h1>
<ul id="sandwich-line">
</ul>
</section>
<section id="coffee">
<h1>Coffee line</h1>
<ul id="coffee-line">
</ul>
</section>
<section id="everything-else">
<h1>Everythin else line</h1>
<ul id="everything-else-line">
</ul>
</section>
我现在有这个
///////////////////////////////////
// HTML Queue
///////////////////////////////////
// Grab the Queue element and
var ulList = document.getElementById('queue').getElementsByTagName('li');
for(var i = 0; i < ulList.length;){
// this finds out what they "want" based on the attribute
var ulOrder = ulList[i].getAttribute("want");
// To organize the line we can use if statements
if (ulOrder === "coffee"){
coffeeLine.appendChild(ulList[i]);
} else if (ulOrder === "sandwich"){
sandLine.appendChild(ulList[i]);
} else {
elseLine.appendChild(ulList[i]);
}
}
工作!
但是当我改变我的for循环添加增量时(就像我一直做的那样)
for (var i = 0; i < ulList.length; i++){
我最终得到了这样的东西
不工作
现在我也试着使用
for (var i in ulList) {
和我得到相同的结果,因为它不工作
谁能帮我理解我显然错过了什么?谢谢你!
您可能已经注意到,appendChild()
将元素移动到文档中的新位置。getElementsByTagName()
返回一个类似数组的对象,它是活的,也就是说,当你从它的"作用域"中添加或删除元素时,它会自动更新。
您可以通过每次从ulList
追加i
递减1来修复您的循环。
相关文章:
- 在for循环中使用多维数组设置google.maps.Marker图标
- Javascript-用于展开数组的递归/for循环
- JavaScript-将for循环的多个结果推送到数组中
- 将值从for循环(在另一个for循环中)JavaScript中推送到数组
- 使用条件for循环更新数组-Javascript
- 使用for循环填充document.getelementbyid中的数组
- 将推入式数组与for一起使用..在..循环中
- For循环与数组不起作用
- 将数组与For循环进行比较
- 如何在 for 循环中访问 json 数组字段的名称
- 访问带有 for 循环中的计数器的数组
- 使用RegExp循环数组而不是for循环(Javascript)
- JavaScript:如何在 for 循环期间跳过数组中的当前项目?(继续?
- Javascript:数组和For循环基础知识
- 如何使用javascript中的for循环成对检索数组元素
- 如何使用for循环语句通过Ajax发送大数据数组
- 如何在JavaScript中正确地将对象从for循环推送到数组
- 对象作为关联数组:for循环
- Howler.js - 从数组/for循环中引用和触发文件
- 通过输入字段和php数组+ for循环声明和使用变量