首页 > JSON.stringify 序列化数组出现问题

JSON.stringify 序列化数组出现问题

本意是想过滤掉数组中的值为null的项,但是却发现了一个神奇的问题,代码如下

        var arr = [1,2,3,null,5];

        JSON.stringify(arr,function(key,value){
            if (value === null) {
                return undefined;
            } else {
                return value;
            }
        })

在最新的firefox 41和chrome 45中均存在这个问题
运行返回的结果是

"[1,2,3,null,5]"

很明显,null没有被过滤掉,经过调试,发现函数第一次执行时,value的值居然是整个数组,这是怎么回事?


Note: You cannot use the replacer function to remove values from an array. If you return undefined or a function then null is used instead.
— https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

认真阅读文档诶...


楼上公子正解, 过滤了再 stringify,

【热门文章】
【热门文章】