簡體   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