简体   繁体   English

Node.js中的jQuery.each()?

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

I have to loop in a JSON array to get some informations in node , but I only know how to to this using $.each() in jQuery. 我必须循环一个JSON数组来获取node一些信息,但我只知道如何在jQuery中使用$.each() So I want to know if there are any alternative for the $.each jQuery function in node.js? 所以我想知道node.js中的$.each jQuery函数是否还有其他选择?

You can use this 你可以用它

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

Where myobject could be your JSON data myobject可能是你的JSON数据

Check out the answer here: Looping through JSON with node.js 看看这里的答案: 通过node.js循环使用JSON

You should use the native for ( key in obj ) iteration method: 您应该使用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
    }
}

If you're dealing with an array, just use a regular for loop: 如果您正在处理数组,只需使用常规for循环:

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

Alternatively, you can use the array's native forEach method, which is a tad slower , but more concise: 或者,您可以使用数组的本机forEach方法, 这有点慢 ,但更简洁:

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

In nodejs I found Array.forEach(callback) to best suite my needs. 在nodejs中,我发现了Array.forEach(callback)以满足我的需求。 It works just like jQuery: 它就像jQuery一样工作:

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

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

jQuery is just javascript, you can do the loop yourself. jQuery只是javascript,你可以自己做循环。

I don't know the structure of the JSON array you're looping but you can use a for..in method to get every property of an object. 我不知道你循环的JSON数组的结构,但你可以使用for..in方法来获取对象的每个属性。

So you would do something like: 所以你会做类似的事情:

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

Also you can use the forEach method that Array provides, that works in a similar way that jQuerys .each() 你也可以使用Array提供的forEach方法,它的工作方式与jQuerys .each()类似。

good luck! 祝好运!

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

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