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


当前回答

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

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 破坏和扩散操作器的插槽

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

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

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

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

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

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

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

这是一个非分散列表的 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标签变成绿色

使用字符串作为函数时要小心:函数是由背景外创建的,并且应该仅在您对变量调节的确定情况下使用。

你可以使用:

ForEach theArray.forEach(功能(序列,索引) { console.log(索引); console.log(序列); }; for(var i=0; i<theArray.length; i++) { console.log(i) } 地图 theArray.map(x => console.log(x));地图 theArray.filter(x => console.log(x));

而且还有很多其他人为 iteration。

我會說,為 / 是走的路:

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( )的文章。