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


当前回答

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

其他回答

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

如果您正在使用 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].
}

最接近您的想法的方式将是使用 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 6 破坏和扩散操作器的插槽

以下示例将使用陈述和.forEach 方法. 示例 6, 7 和 8 可以使用任何功能漏洞,如.map,.filter,.reduce,.sort,.every,.some. 有关这些方法的更多信息,请参阅 Array Object。

例子3:用密钥和价值跳动

示例4:获取对象属性在线

以此为主,以此为主,以此为主,以此为主。

示例7: 示例4 是否使用.forEach

示例8: 示例5 是否使用.forEach

如果您想保持代码的功能,请使用地图:

theArray.map(instance => do_something);

在这种情况下,您将为未来的操作创建一个新的序列,并将错过任何不需要的副作用。