2 u014603095 u014603095 于 2015.06.10 09:07 提问

关于JS的类型问题!!!

var testStr = '[{"aa":"a1","bb":"b1","cc":"c1","dd":"d1"},{"aa":"a2","bb":"b2","cc":"c2","dd":"d2"},{"aa":"a3","bb":"b3","cc":"c3","dd":"d3"},{"aa":"a4","bb":"b4","cc":"c4","dd":"d4"},{"aa":"a5","bb":"b5","cc":"c5","dd":"d5"}]';

这个testStr是什么类型?如何给它添加新的内容?

补充:这样this.objectlist = eval('('+testStr+')');,有什么用哦?eval后得到的什么?

9个回答

danielinbiti
danielinbiti   Ds   Rxr 2015.06.10 09:12
已采纳
这是json格式的字符串
 <!DOCTYPE html>
<html>
<body>
<script>
var testStr = '[{"aa":"a1","bb":"b1","cc":"c1","dd":"d1"},{"aa":"a2","bb":"b2","cc":"c2","dd":"d2"},{"aa":"a3","bb":"b3","cc":"c3","dd":"d3"},{"aa":"a4","bb":"b4","cc":"c4","dd":"d4"},{"aa":"a5","bb":"b5","cc":"c5","dd":"d5"}]';
var jsontext = eval('('+testStr+')');
for(var i=0;i<jsontext.length;i++){
   document.write(jsontext[i].aa+',');
   jsontext[i]['添加内容']='cccc';
   document.write(jsontext[i].添加内容+',');
}
</script>

</body>
</html>

xya_zone
xya_zone   2015.06.10 11:07

testStr,是一个String类型,用eval计算后是Ojbect对象,
var testStr = '[{"aa":"a1","bb":"b1","cc":"c1","dd":"d1"},{"aa":"a2","bb":"b2","cc":"c2","dd":"d2"},{"aa":"a3","bb":"b3","cc":"c3","dd":"d3"},{"aa":"a4","bb":"b4","cc":"c4","dd":"d4"},{"aa":"a5","bb":"b5","cc":"c5","dd":"d5"}]';
alert(typeof(testStr));---->string
var s= eval('('+testStr+')');
alert(s)----->则是一个数组对象
alert(s[0].aa);---->a1
alert(s[1].aa);---->a2

bdmh
bdmh   Ds   Rxr 2015.06.10 09:11

得到的是json对象,就可以直接用 objectlist.xxx访问里面的对象

showbo
showbo   Ds   Rxr 2015.06.10 09:18

testStr是字符串,eval后得到json对象

cuiwei1026522829
cuiwei1026522829   Ds   Rxr 2015.06.10 09:35

是json字符串,你可以在前台直接解析她!

oQingXin12345
oQingXin12345   2015.06.10 09:47

testStr是json,要给他添加新内容,如果新内容少的话可以按照上面的格式直接拼进去,新内容多得话可以用JsonArray或者JsonObject等类将新的内容自动转换为json再添进去。具体可以问度娘了

huangfu_chunfeng
huangfu_chunfeng   2015.06.10 10:31
这个testStr如果是在html里面就是一个var类型也就是string类型,
 eval计算字符串,得到的是一个数组不是JSON

也就是这个数组 去掉引号[{"aa":"a1","bb":"b1","cc":"c1","dd":"d1"},{"aa":"a2","bb":"b2","cc":"c2","dd":"d2"},{"aa":"a3","bb":"b3","cc":"c3","dd":"d3"},{"aa":"a4","bb":"b4","cc":"c4","dd":"d4"},{"aa":"a5","bb":"b5","cc":"c5","dd":"d5"}];

beacon_2011
beacon_2011   Rxr 2015.06.10 15:11

var 是弱数据类型,后边的数据是什么类型它就是什么类型

frank_20080215
frank_20080215   2015.06.10 12:41

json数据包
eval后得到
{"aa":"a1","bb":"b1","cc":"c1","dd":"d1"},{"aa":"a2","bb":"b2","cc":"c2","dd":"d2"},{"aa":"a3","bb":"b3","cc":"c3","dd":"d3"},{"aa":"a4","bb":"b4","cc":"c4","dd":"d4"},{"aa":"a5","bb":"b5","cc":"c5","dd":"d5"}

Csdn user default icon
上传中...
上传图片
插入图片