从JSON数组中删除行会留下'null'

S16*_*S16 10 javascript jquery json

http://jsfiddle.net/J2KuY/

在test2中,您可以看到,它不是从数组中删除节点,而是用'null'替换节点.

我做错了什么,怎么能完全删除它?

编辑:使用Splice而不是删除.更新了小提琴:http://jsfiddle.net/J2KuY/1/

gal*_*hen 8

使用拼接:

http://www.w3schools.com/jsref/jsref_splice.asp

  • w3schools,嗯?https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice (9认同)
  • @ Dr.Molle是的,我不打算链接到PDF,我也不会链接到ECMAScript.我将链接到权威资源,如供应商的标准实现,易于阅读,索引,并且只是有问题的功能.W3Schools经常出错,过时且难以理解. (3认同)

Jos*_*eph 3

这是一个带有链接的示例

\n\n
//say you have these arrays\nvar test1 = [{\n    "Country": "Spain",\n    "info info1": 0.329235716,\n    "info info2": 0.447683684,\n    "info info3": 0.447683747},\n{\n    "Country": "Chile",\n    "info info1": 1.302673893,\n    "info info2": 1.357820775,\n    "info info3": 1.35626442},\n{\n    "Country": "USA",\n    "info info1": 7.78805016,\n    "info info2": 26.59681951,\n    "info info3": 9.200900779}];\n\nvar test2 = [{\n    "Country": "Germany",\n    "info info1": 0.329235716,\n    "info info2": 0.447683684,\n    "info info3": 0.447683747},\n{\n    "Country": "China",\n    "info info1": 1.302673893,\n    "info info2": 1.357820775,\n    "info info3": 1.35626442},\n{\n    "Country": "France",\n    "info info1": 7.78805016,\n    "info info2": 26.59681951,\n    "info info3": 9.200900779}];\n\n\n//similar to jQuery, wrap them in an object\nfunction $W(param) {\n    var obj = {};\n\n    //set data\n    obj.data = param;\n\n    //augment the object with a remove function\n    obj.remove = function(key, val) {\n        var i = 0;\n        //loop through data\n        while (this.data[i]) {\n            if (this.data[i][key] === val) {\n                //if we have that data, splice it\n                //splice changes the array length so we don\'t increment\n                this.data.splice(i, 1);\n            } else {\n                //else move on to the next item\n                i++;\n            }\n        }\n        //be sure to return the object so that the chain continues\n        return this;\n    }\n\n    //return object for operation\n    return obj\n}\n\n//the following will look strangely similar to jQuery\n\n//remove chile, then USA\nvar result1 = $W(test1).remove(\'Country\', \'Chile\').remove(\'Country\', \'USA\');\n\n//remove germany and china\nvar result2 = $W(test2).remove(\'Country\', \'China\').remove(\'Country\', \'Germany\');\n\n//should only have spain and france\n$(\'#test2\').val(JSON.stringify(result1)+JSON.stringify(result2));\xe2\x80\x8b\n
Run Code Online (Sandbox Code Playgroud)\n