用javascript对多维数组进行字符串化
Stringify a multi-dimension array with javascript
我正在为书籍创建发票,并打算通过ajax提交。我试图对发票中的书籍数组进行json编码,但我一直得到一个空值
//create item list
var order_items = [];
$('#mi_books tbody tr.userbooks').each(function(index)
{
var bookisbn = $(this).find('td .mi_isbn').text();
var bookdata = [];
bookdata['isbn'] = bookisbn;
bookdata['title'] = $(this).find('.mi_title').text();
bookdata['qty'] = $(this).find('.mi_qty').text();
bookdata['price'] = $(this).find('.mi_price').text();
order_items.push(bookdata);
});
alert(JSON.stringify(order_items));
alert(order_items.toString());
console.log(order_items);
alert(JSON.stringify(order_items));
输出:[[]]
alert(order_items.toString());
输出:blank
console.log(order_items);
输出:
Array[1]
0: Array[0]
isbn: "9781401216672"
length: 0
price: "1007"
qty: "1"
title: "Batman: The Killing Joke"
__proto__: Array[0]
length: 1
__proto__: Array[0]
我的数组正在创建中,但不知何故,我似乎无法对其进行json编码?我做错什么了吗?
Array
和Object
是不同的野兽。您的bookdata
不是一个数组,而是一个对象,因此,您应该使用创建它
var bookdata = {};
与常规对象相比,JSON.stringify()
对数组进行了不同的序列化(仅序列化UInt32的属性)。由于您只向bookdata
添加文本属性,因此应该使用以下匿名对象:
var bookdata = {
isbn: bookisbn,
title: $(this).find('.mi_title').text(),
qty: $(this).find('.mi_qty').text(),
price: $(this).find('.mi_price').text()
};
您可以尝试
var order_items = {};
$('#mi_books tbody tr.userbooks').each(function(index)
{
var bookisbn = $(this).find('td .mi_isbn').text();
var bookdata = {
'isbn': bookisbn,
'title': $(this).find('.mi_title').text(),
'qty': $(this).find('.mi_qty').text(),
'price': $(this).find('.mi_price').text()
};
order_items[index] = bookdata;
});
alert(JSON.stringify(order_items));
你唯一的错误是试图创建关联数组,而不是使用对象,这可以做到
相关文章:
- 将JSON转换为typescript中的字符串数组
- 在Javascript中将一个值和字符串数组转换为if语句
- 如何将正则表达式包含到字符串数组中
- JavaScript:将字符串数组转换为文本区域
- Knockout中的字符串数组
- 拆分字符串数组(JavaScript)后未定义
- 使用Javascript获取两个字符串之间的字符串数组
- 打印从Spring MVC Controller发送的字符串数组只显示“;toJSON”;在javascript中
- 将一个字符串数组解析为一个新的数组javascript
- AngularJS - 从字符串数组中连续更改文本
- 使用字符串数组中的字符填充 HTML 表
- 如何在 Javascript 中将字符串数组列表插入到表行中
- 创建二维字符串数组
- 如何从字符串数组中获取子字符串数组
- 如何将字符串数组转换为简单数组
- 按字母顺序、数字顺序和特殊字符对字符串数组进行排序
- 如何从字符串数组中获得8个随机唯一元素
- json_encode($myVar);正在给出地图,我想要一个字符串数组
- 函数,返回javascript中两个字符串数组的差值
- Javascript字符串数组转换为用逗号分隔的多个字符串