我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
使用到...可能的地方
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 */
}
查看更多例子的参考,链接到规格和与与与与与之间的差异,或者可能检查这个教程,以了解它们如何不同。
其他回答
var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
console.log("Index" + index);
console.log("Element" + item);
})
您可以使用图书馆获得此功能(我建议 Underscore.js),使用一个简单的在路径。
for (var instance in objects) {
...
}
但是,请注意,可能有理由使用一个更简单的旋转(见 Stack Overflow 问题 为什么使用“为”与序列调节这样的坏想法?)
var instance;
for (var i=0; i < objects.length; i++) {
var instance = objects[i];
...
}
在 jQuery 中,有三种实施。
var a = [3,2];
$(a).each(function(){console.log(this.valueOf())}); //Method 1
$.each(a, function(){console.log(this.valueOf())}); //Method 2
$.each($(a), function(){console.log(this.valueOf())}); //Method 3
最接近您的想法的方式将是使用 Array.forEach() 接受关闭函数,该函数将适用于序列的每个元素。
myArray.forEach(
(item) => {
// Do something
console.log(item);
}
);
另一种可行的方式是使用 Array.map() 以相同的方式工作,但它也需要所有值,你返回并返回它们在一个新的序列(基本上将每个元素地图到一个新的),如下:
var myArray = [1, 2, 3];
myArray = myArray.map(
(item) => {
return item + 1;
}
);
console.log(myArray); // [2, 3, 4]
ECMAScript 5(JavaScript版本)与Arrays一起工作:
forEach - 通过序列中的每个项目,并与每个项目所需的一切。
['C', 'D', 'E'].forEach(function(element, index) {
console.log(element + " is #" + (index+1) + " in the musical scale");
});
// Output
// C is the #1 in musical scale
// D is the #2 in musical scale
// E is the #3 in musical scale
在这种情况下,更有兴趣使用一些内置功能在序列上运行。
地图 - 它创建一个新的序列,结果是呼叫回复功能. 这个方法是很好的使用,当你需要格式化的元素的序列。
// Let's upper case the items in the array
['bob', 'joe', 'jen'].map(function(elem) {
return elem.toUpperCase();
});
// Output: ['BOB', 'JOE', 'JEN']
减少 - 正如名称所说,它将序列减少到一个单一值,通过在当前元素中传输的特定函数和以前的执行结果。
[1,2,3,4].reduce(function(previous, current) {
return previous + current;
});
// Output: 10
// 1st iteration: previous=1, current=2 => result=3
// 2nd iteration: previous=3, current=3 => result=6
// 3rd iteration: previous=6, current=4 => result=10
每次 - 返回真实或虚假,如果序列中的所有元素在呼叫回复函数中通过测试。
// Check if everybody has 18 years old of more.
var ages = [30, 43, 18, 5];
ages.every(function(elem) {
return elem >= 18;
});
// Output: false
过滤器 - 非常相似于每一个,除了过滤器返回一个序列的元素返回真实的给定的功能。
// Finding the even numbers
[1,2,3,4,5,6].filter(function(elem){
return (elem % 2 == 0)
});
// Output: [2,4,6]
推荐文章
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- 如何读一个文本文件到一个列表或数组与Python
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 如何在Python中将十六进制字符串转换为字节?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法