首页 > 解决方案 > 数据表:未捕获的类型错误:减少没有初始值的空数组

问题描述

我有下面的功能

footerCallback: function ( row, data, start, end, display ) {
    var api = this.api();
    // Remove the formatting to get integer data for summation
    var intVal = function ( i ) {

        return typeof i === 'string' ?
            i.replace(/[\$,]/g, '')*1 :
            typeof i === 'number' ?
                i : 0;

    };
    var i;
    for (i = 1; i <=96; i++) { 
        if (api.column(i).data().length){
            console.log('[+] api.column( i ).data()');
            console.log(api.column( i ).data());
            var total = api.column( i ).data().reduce( function (a, b) {
                console.log( intVal(a) + intVal(b));
                return intVal(a) + intVal(b);
                }) 
            }
        else { 
            total = 0
        };
        // Total over this page
        if (api.column(i).data().length){
            var pageTotal = api.column( i, { page: 'current'} ).data().reduce( function (a, b) {
                return intVal(a) + intVal(b);
            })
        }
        else{ 
            pageTotal = 0
        };

        // Update footer
        $( api.column(i).footer() ).html(total);
    }

    // Total over all pages

},

它将列中的值相加并将其添加到总数中。所以我有两个版本。一种有效,一种无效。两个页面中使用的代码完全相同

工作控制台.Log

在此处输入图像描述

损坏的 Console.Log

错误:Uncaught TypeError: Reduce of empty array with no initial value

在此处输入图像描述

我注意到损坏的文本有红色文本,并且每个 0 或 1 周围都有双引号。

奇怪的是....损坏的版本完成了与总数一样多的工作,但是由于错误,页面仍然损坏

标签: javascriptjquerydatatables

解决方案


删除以下工作 - 它未被使用但仍然导致问题

 // Total over this page
        if (api.column(i).data().length){
            var pageTotal = api.column( i, { page: 'current'} ).data().reduce( function (a, b) {
                return intVal(a) + intVal(b);
            })
        }
        else{ 
            pageTotal = 0
        };

推荐阅读