首页 > 解决方案 > 如何遍历这种 JavaScript 数组?

问题描述

我正在将数据返回到我的DataTables表中,但我无法遍历以下数组:

["BREAKFAST (Vegetables)", "LUNCH-DINNER (Vegetables)"]

我尝试了下面的代码,但它只打印了第一项

{data: null,
    render: function(data, type, row, meta) {
        var categoriesNamesList = '';
        //loop through all the row details to build output string
        for (var item in row.categories_names) {
            var r = row.categories_names[item];
            //Check if r is NULL or Empty then skip
            if(r){
                categoriesNamesList = '<ul><li>'+ r + '</li></ul>';
            }
        }
        return categoriesNamesList;

    }
}

标签: javascriptarraysdatatables

解决方案


您实际上可以通过以下方式.map(...)在数组上使用 a (假设):row.categories_names

render: function(data, type, row, meta) {
    return row.categories_names.map(function(item) {
        return '<ul><li>'+item+'</li></ul>';
    });
}

它可能更简单。让我知道它是否有效。


推荐阅读