繁体   English   中英

Node.js中的jQuery.each()?

[英]jQuery.each() in Node.js?

我必须循环一个JSON数组来获取node一些信息,但我只知道如何在jQuery中使用$.each() 所以我想知道node.js中的$.each jQuery函数是否还有其他选择?

你可以用它

for (var name in myobject) {
   console.log(name + ": " + myobject[name]);
}

myobject可能是你的JSON数据

看看这里的答案: 通过node.js循环使用JSON

您应该使用native for ( key in obj )迭代方法:

for ( var key in yourJSONObject ) {
    if ( Object.prototype.hasOwnProperty.call(yourJSONObject, key) ) {
        // do something
        // `key` is obviously the key
        // `yourJSONObject[key]` will give you the value
    }
}

如果您正在处理数组,只需使用常规for循环:

for ( var i = 0, l = yourArray.length; i < l; i++ ) {
    // do something
    // `i` will contain the index
    // `yourArray[i]` will have the value
}

或者,您可以使用数组的本机forEach方法, 这有点慢 ,但更简洁:

yourArray.forEach(function (value, index) {
    // Do something
    // Use the arguments supplied. I don't think they need any explanation...
});

在nodejs中,我发现了Array.forEach(callback)以满足我的需求。 它就像jQuery一样工作:

myItems.forEach(function(item) {
   console.log(item.id);
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

jQuery只是javascript,你可以自己做循环。

我不知道你循环的JSON数组的结构,但你可以使用for..in方法来获取对象的每个属性。

所以你会做类似的事情:

    for( var i = 0; len = jsonArray.length; i < len; i++) {
        for(var prop in jsonArray[i]) {
         //do something with jsonArray[i][prop], you can filter the prototype properties with hasOwnProperty
        }
}

你也可以使用Array提供的forEach方法,它的工作方式与jQuerys .each()类似。

祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM