javascript Jquery - JSON.stringify,数组为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3602713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery - JSON.stringify, array is empty
提问by Peter
i hope somebody can help me, the array value is empty in the post.
我希望有人可以帮助我,帖子中的数组值为空。
$(function start() {
c_all = new Array('#div { font-color:#ff0000; border:1px solid #00ff00; }', '#div_2 { font-color:#ff0000; }', '.line2 { font-color:#00ffff; }');
css(c_all);
});
function css(x) {
values = new Array();
for (i = 0; i < x.length; i++) {
c0_selector = '' + x[i].match(/^.*{/) + '';
c0_selector = c0_selector.replace(/\s*/g, '');
c0_selector = c0_selector.replace(/{/, '');
x[i] = x[i].replace(/^.*{/, '');
x[i] = x[i].replace(/}/, '');
c0_arr = x[i].split(';');
values['' + c0_selector + ''] = new Array();
$('#log').append(''+c0_selector+'<br />');
for (i2 = 0; i2 < c0_arr.length; i2++)
{
values[''+c0_selector+''][i2] = c0_arr[i2].split(':');
$('#log').append(''+c0_arr[i2]+'<br />');
}
}
$.ajax({
type: 'post',
data: JSON.stringify(values),
contentType: 'application/json',
dataType: 'json'
});
}
working example -> http://www.jsfiddle.net/V9Euk/448/
工作示例 -> http://www.jsfiddle.net/V9Euk/448/
Thanks in advance! Peter
提前致谢!彼得
回答by user113716
Try making valuesan Object, (like it should be in javascript for named keys).
尝试创建values一个对象,(就像它应该在 javascript 中用于命名键)。
var values = {};
Also, it is a reallygood idea to declare your variables with the varkeyword, so you're not creating global variables.
此外,使用关键字声明变量是一个非常好的主意var,这样您就不会创建全局变量。
Also, no need for '' + c0_selector + ''since you already have a String. Just do c0_selector.
此外,不需要,'' + c0_selector + ''因为您已经有一个字符串。就做c0_selector。
Finished product logs the populated Object. http://www.jsfiddle.net/V9Euk/450/
成品记录填充的对象。http://www.jsfiddle.net/V9Euk/450/
回答by ChaosPandion
This is straight from the ECMAScript spec.
这直接来自 ECMAScript 规范。
The abstract operation JA(value) serializes an array. It has access to the stack, indent, gap, and space of the invocation of the stringify method. The representation of arrays includes only the elements between zero and array.length – 1 inclusive. Named properties are excluded from the stringification. An array is stringified as an open left bracket, elements separated by comma, and a closing right bracket.
抽象操作 JA(value) 序列化一个数组。它可以访问调用 stringify 方法的堆栈、缩进、间隙和空间。数组的表示仅包括介于 0 和 array.length – 1 之间的元素。命名属性从字符串化中排除。数组被字符串化为左左括号、逗号分隔的元素和右括号。
Basically any named properties are excluded from the result.
基本上所有命名属性都从结果中排除。

