我如何通过一个序列中的所有输入,使用JavaScript?


当前回答

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

其他回答

一个 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
  }
);

如果你想通过一系列用箭函数的对象旋转:

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'); })

根据新更新 ECMAScript 6 (ES6) 和 ECMAScript 2015 的功能,您可以使用以下选项:

对于洛普

for(var i = 0; i < 5; i++){
  console.log(i);
}

// Output: 0,1,2,3,4

上一篇:在洛普斯

let obj = {"a":1, "b":2}

for(let k in obj){
  console.log(k)
}

// Output: a,b

Array.forEach( )

let array = [1,2,3,4]

array.forEach((x) => {
  console.log(x);
})

// Output: 1,2,3,4

為...LOPS

let array = [1,2,3,4]

for(let x of array){
  console.log(x);
}

// Output: 1,2,3,4

當LOPS

let x = 0

while(x < 5){
  console.log(x)
  x++
}

// Output: 1,2,3,4

此分類上一篇: while loops

let x = 0

do{
  console.log(x)
  x++
}while(x < 5)

// Output: 1,2,3,4

现在一个简单的解决方案是使用 underscore.js 图书馆,它提供了许多有用的工具,如每一个,并将自动将工作分配给原住民的Each 如果可用。

一个CodePen的例子,它是如何工作:

var arr = ["elemA", "elemB", "elemC"];
_.each(arr, function(elem, index, ar)
{
...
});

看也

在 for_each...in(MDN)中,它解释说,对于每个(对象变量)是作为ECMA-357(EAX)标准的一部分,而对于(MDN)来说,它描述了使用(对象变量)为(对象变量)作为和谐(ECMAScript 6)提议的一部分的下一个方法。

如果你想使用 forEach(),它会看起来像 -

theArray.forEach ( element => {
    console.log(element);
});

如果你想使用(),它会看起来像 -

for(let idx = 0; idx < theArray.length; idx++){
    let element = theArray[idx];
    console.log(element);
}