How to iterate a json array nullsafe?

This question already has an answer here:

  • For-each over an array in JavaScript? 23 answers

  • 试试这个

    (offer.products || []).forEach(function(product) {
       console.log(product);
    });
    

    Just add the fitting checks:

    if (offer.products) { //blocks products==null and products==undefined
        offer.products.forEach(function(product) {
            console.log(product);
        });
    }
    

    Empty should not be a problem, since forEach should not do anything if products is empty.

    链接地址: http://www.djcxy.com/p/12074.html

    上一篇: 对于...中的字符串数组

    下一篇: 如何迭代一个JSON数组nullsafe?