我如何通过一个序列中的所有输入,使用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);
在这种情况下,您将为未来的操作创建一个新的序列,并将错过任何不需要的副作用。
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 在Bash中模拟do-while循环
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何确定一个数组是否包含另一个数组的所有元素
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- 加快R中的循环操作
- 给定一个数字数组,返回所有其他数字的乘积的数组(不除法)
- 多维数组如何在内存中格式化?