我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
如果你不关心空白:
var x;
while(x = y.pop()){
alert(x); //do something
}
x 将包含 y 的最后值,并将从序列中删除。
其他回答
我来自Python,我发现这种方式更清晰。
theArray 是 array,例子是 array 的元素:
for (let instance of theArray)
{
console.log("The instance", instance);
}
或
for (instance in theArray)
{
console.log("The instance", instance);
}
与比较:
theArray.forEach(function(instance) {
console.log(instance);
});
但是,在一天结束时,两人都在做同样的事情。
如果您想保持代码的功能,请使用地图:
theArray.map(instance => do_something);
在这种情况下,您将为未来的操作创建一个新的序列,并将错过任何不需要的副作用。
如果您正在使用 jQuery 图书馆,您可以使用 jQuery.each:
$.each(yourArray, function(index, value) {
// do your stuff here
});
编辑:
作为一个问题,用户想要代码在JavaScript而不是jquery,所以编辑是
var length = yourArray.length;
for (var i = 0; i < length; i++) {
// Do something with yourArray[i].
}
使用到...可能的地方
async /await support |
Skips non-numeric props | Immutable index | |
---|---|---|---|
for...of |
✅ | ✅ | ✅ |
forEach() |
❌ | ✅ | ✅ |
for...in |
✅ | ❌ | ✅ |
Regular for |
✅ | ✅ | ❌ |
正如上面的表中可以看到的那样,它应该随时随地使用,因为它支持非同步功能,并通过随机修改曲线指数来阻止非数字特性。
合成
const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const num of nums) {
/* Do something with num */
}
查看更多例子的参考,链接到规格和与与与与与之间的差异,或者可能检查这个教程,以了解它们如何不同。
Lambda Syntax 通常不适用于 Internet Explorer 10 或更低版本。
我通常使用
[].forEach.call(arrayName,function(value,index){
console.log("value of the looped element" + value);
console.log("index of the looped element" + index);
});
如果您是一个 jQuery 粉丝,并且已经有一个 jQuery 文件运行,您应该逆转指数和值参数的位置。
$("#ul>li").each(function(**index, value**){
console.log("value of the looped element" + value);
console.log("index of the looped element" + index);
});
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何在c#中连接列表?
- 应该……接住环内还是环外?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?