我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
console.log("Index" + index);
console.log("Element" + item);
})
其他回答
如果你需要一个圆体的工作进行序列(而不是平行),一个等待在圆体将等待承诺安排之前继续。
const a = [“a”,“b”,“c”]; for (let index = a.length - 1; index >= 0; --index) { const element = a[index]; console.log(element); }
(ES2015+) 用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于用于
Caveat 为主机提供的物品
如果你想在一个序列上旋转,请使用标准的三部分旋转。
for (var i = 0; i < myArray.length; i++) {
var arrayItem = myArray[i];
}
您可以通过缓存 myArray.length 或向后转向它获得某些性能优化。
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]
如果你想通过一系列用箭函数的对象旋转:
let arr = [{name:'john', age:50}, {name:'clark', age:19}, {name:'mohan', age:26}]; arr.forEach((person)=>{ console.log('I am ' + person.name + ' and I am ' + person.age + ' old'); })
某些 C 风格的语言使用 foreach 通过列表旋转。 在 JavaScript 中,这与 for..in 旋转结构进行:
var index,
value;
for (index in obj) {
value = obj[index];
}
要避免通过对象的原型继承的阅读值,只需检查是否属于对象的财产:
for (i in obj) {
if (obj.hasOwnProperty(i)) {
//do stuff
}
}
此外,ECMAScript 5 已添加一个 forEach 方法到 Array.prototype 可以用来列出一个序列,使用一个字符串(多字符串在文件中,所以你仍然可以使用它在更老的浏览器):
arr.forEach(function (val, index, theArray) {
//do stuff
});
重要的是要注意的是,当通话返回虚假时,Array.prototype.forEach 不会破裂。 jQuery 和 Underscore.js 提供各自的变量,以提供可以短循环的漏洞。
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 在Bash中模拟do-while循环
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何确定一个数组是否包含另一个数组的所有元素
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- 加快R中的循环操作
- 给定一个数字数组,返回所有其他数字的乘积的数组(不除法)
- 多维数组如何在内存中格式化?