我如何通过一个序列中的所有输入,使用JavaScript?
当前回答
如果你想使用 forEach(),它会看起来像 -
theArray.forEach ( element => {
console.log(element);
});
如果你想使用(),它会看起来像 -
for(let idx = 0; idx < theArray.length; idx++){
let element = theArray[idx];
console.log(element);
}
其他回答
一个 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
}
);
我来自Python,我发现这种方式更清晰。
theArray 是 array,例子是 array 的元素:
for (let instance of theArray)
{
console.log("The instance", instance);
}
或
for (instance in theArray)
{
console.log("The instance", instance);
}
与比较:
theArray.forEach(function(instance) {
console.log(instance);
});
但是,在一天结束时,两人都在做同样的事情。
如果你不关心空白:
var x;
while(x = y.pop()){
alert(x); //do something
}
x 将包含 y 的最后值,并将从序列中删除。
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);
});
这是一个非分散列表的 iterator,指数从0开始,这是处理document.getElementsByTagName或document.querySelectorAll时的典型场景)
function each( fn, data ) {
if(typeof fn == 'string')
eval('fn = function(data, i){' + fn + '}');
for(var i=0, L=this.length; i < L; i++)
fn.call( this[i], data, i );
return this;
}
Array.prototype.each = each;
使用例子:
例子 #1
var arr = [];
[1, 2, 3].each( function(a){ a.push( this * this}, arr);
arr = [1, 4, 9]
例子 #2
each.call(document.getElementsByTagName('p'), "this.className = data;",'blue');
每個 p 標籤都會得到 class="blue"
例子 #3
each.call(document.getElementsByTagName('p'),
"if( i % 2 == 0) this.className = data;",
'red'
);
每個其他 p 標籤都會得到 class="red">
例子 #4
each.call(document.querySelectorAll('p.blue'),
function(newClass, i) {
if( i < 20 )
this.className = newClass;
}, 'green'
);
最后,第一个20个蓝色P标签变成绿色
使用字符串作为函数时要小心:函数是由背景外创建的,并且应该仅在您对变量调节的确定情况下使用。
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 在Bash中模拟do-while循环
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何确定一个数组是否包含另一个数组的所有元素
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- 加快R中的循环操作
- 给定一个数字数组,返回所有其他数字的乘积的数组(不除法)
- 多维数组如何在内存中格式化?