动态创建/创建变量's字典并打印
Create/ creating the variable's dict dynamically and print
我想在alert中打印字典a,(这是可能的吗?)或者在第三个文本区域(3)中使用id=p
打印。我读了这个问题,我用了
document.getElementById("p").value=JSON.stringify(a);;
alert("myObject is " + a.toSource());
console.log(a);
这些不起作用。示例如下:
<!DOCTYPE HTML>
<html>
<head>
<title>Example - print the dict</title>
</head>
<body>
<input id = 'button1' type = 'button' value = 'print the dict' onclick="updateHistory()"/>
<script type = 'text/javascript'>
var count ="?foo=1&oo=298529982";
function updateHistory()
{
var a = new Array();
for (var i = 0; i < document.formparam.elements.length; i++)
{
var field = document.formparam.elements[i];
a[field.name] = field.value;
}
document.getElementById("p").value=JSON.stringify(a);;
alert("myObject is " + a.toSource());
console.log(a);
}
</script>
<form method="GET" name="formparam" id="formparam" ><table><tr><td><textarea name="name" >john</textarea></td><td><textarea name="surname">jackold</textarea></td></tr></table></form>
<textarea id="p"></textarea>
</body>
</html>
在数组上使用JSON.stringify()
将像这样遍历数组:
for (var i = 0; i < a.length; ++i) {
// process value of a[i]
}
但是因为您使用a[field.name]
向对象添加属性,所以这些属性不会添加到数组项列表中,不像a.push(value)
。因此,JSON.stringify()
将打印[]
。
你应该:
定义
a
为对象,即var a = {};
自己遍历键:
for (var k in a) { if (a.hasOwnProperty(k)) { // process value of a[k] } }
var a = new Array();
var a = {};
或var a = new Object();
JavaScript中没有字典,但是,您可以使用对象作为键/值存储。要将object
通知为JSON,只需执行alert(JSON.stringify(a));
。
相关文章:
- 用Javascript/PHP创建字典
- 在JSON中创建一个数据对(不是字典,而是两个独立的数据)
- 用Javascript从一个大的2D数组中编程创建一个字典
- 如何在AngularJS中创建类似字典的模型绑定
- 有没有办法在应用程序脚本中使用JavaScript为对象创建方法字典
- 如何在 javascript 中创建字典键值对数组
- 从JavaScript创建字典cookie
- 使用javascript创建新字典
- TypeScript 创建某个类型的字典
- 使用自定义函数从字典中创建列表/数组
- 用javascript从单个JSON响应创建多个字典
- 用Javascript创建一个类似.net的字典对象
- 使用django-template[python]中的json.dump或pprint在字典中逐行创建一个表
- 如何在jquery中创建字典的JSON数组
- 如何在另一个文件或Javascript块中创建字典的新对象
- Javascript不能在IE中创建字典
- 创建一个字典并按属性搜索
- 动态创建/创建变量's字典并打印
- 在这种情况下如何使用GAS来创建字典
- “;字典“;在JavaScript中创建