我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
console.log("Index" + index);
console.log("Element" + item);
})
其他回答
一个 forEach 实施(见 jsFiddle):
function forEach(list,callback) {
var length = list.length;
for (var n = 0; n < length; n++) {
callback.call(list[n]);
}
}
var myArray = ['hello','world'];
forEach(
myArray,
function(){
alert(this); // do something
}
);
var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
console.log("Index" + index);
console.log("Element" + item);
})
Mozilla 文档
/* 获取所有表格 */ document.querySelectorAll(“表格” ).forEach(表格 => { /* 每个表格,添加我们提交的事件 */ form.addEventListener(“提交”,事件 => { event.preventDefault(); // Return false /* 显示它 */ alert(event.target.action); console.log(event.target); }; }; ); <form action="form1.php" > <input type="submit" value="Submit" /> </form
总结:
创建新序列:地图
let arr = [1, 2, 3, 4, 5]; let newArr = arr.map(元素,索引,序列) => {返回元素 * 2; }) console.log(arr); console.log(newArr);
forEach 是一种位于 Array.prototype 的函数,它将作为一个论点采取呼叫回归函数,然后对序列中的每个元素进行此呼叫回归函数,与地图() 函数不同,forEach 函数不会返回任何东西(未定义)。
我會說,為 / 是走的路:
const arr = ['a', 'b', 'c']; for (const v of arr) { console.log(v); // 打印“a”,“b”,“c” }
例如,如果您设置 arr.foo = 'test', for (var v in arr) 将通过 'foo' 密钥旋转. 不同于 forEach(), for/of 不会错过'洞' 在 序列. const arr = ['a', 'c'] 是有效的 JavaScript, 只有 2 个元素是'洞'. 序列功能相当于 ['a', undefined, 'c'].
您可以在此博客中阅读更多关于 for/of vs forEach( )的文章。