为什么我最后在JSON中获得了额外的元素? [英] Why do I get an extra element at the end in JSON?
问题描述
我正在使用某个网站,并且正在使用JSON。我的问题是JSON.parse方法,我用它来发送一个简单的数组,并将值附加到数组中。我总是得到一个额外的元素,我们只是逗号。这是简化的代码:
I'm working on some website, and am using JSON. My problem is the JSON.parse method, I use it to send a simple array, and append to an array the values. And I always get an extra element at the end that us just commas. here is the simplified code:
responseText = '["dummy1", "dummy2", "dummy3", "dummy4"]';
var clientList=[];
try {
JSON.parse(responseText, function(key, val){clientList.push(val)});
} catch (e) {
alert('no');
}
alert(clientList.length);
首先在IE中它根本不起作用(抛出异常)。
First in IE its not working at all (exception is thrown).
第二个chrome结果是clientList是一个包含5个字符串的数组,而最后一个是',,,'。
Second chrome the result is that clientList is an array of 5 strings, while the last one is ',,, '.
为什么是那里有额外的价值吗?我可以摆脱它(不只是在最后弹出阵列)? IE有什么问题?
Why is that extra value there? Can I get rid of it (without just popping the array at the end)? And what is wrong with IE?
推荐答案
这样可行:
responseText = '["dummy1", "dummy2", "dummy3", "dummy4"]';
var clientList=[];
try {
clientList = JSON.parse(responseText);
} catch (e) {
alert('no');
}
IE没有 JSON
作为浏览器的默认值。你需要一个像json2这样的库。
IE doesn't have JSON
as a default in the browser. You need a library like json2.
至于你的问题,那个回调函数实际上是为了转换你的对象而不是构建它。例如:
As for your question, that callback function is really in order to transform your object not build it. For example:
var transformed =
JSON.parse('{"p": 5}', function(k, v) { if (k === "") return v; return v * 2; });
// transformed is { p: 10 }
来自解析
这篇关于为什么我最后在JSON中获得了额外的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!