" push" -ing to array返回它的长度

时间:2018-03-15 00:01:56

标签: javascript arrays

我遇到的问题是,当我解析一个正确返回元素数组的JSON字符串时,我尝试将一个新元素推送到具有空值的数组。

这里的问题是:

console.log('addons ', this.categories[this.editingId - 1].addons);
console.log('parsed ', JSON.parse(this.categories[this.editingId - 1].addons));
console.log('pushed ', JSON.parse(this.categories[this.editingId - 1].addons).push({name:'', price:''}));
  

插件是[{"名称":" Peppers","价格":50},{"名称":&#34 ;辣""价格" 150},{"名称":"鸡""价格" 250},{ "名称":"奶酪""价格" 150},{"名称":"青花菜",& #34;价格":100},{"名称":"玉米""价格" 75},{"名称&#34 ;:"额外的酱油","价格":250},{"名称":"额外的肉","价格&# 34; 350}]

当最后一个参数应该使用新推送的元素记录数组时,最后一个参数返回数组长度的整数。

如何成功推送到阵列?

此处显示最小的示例: https://jsfiddle.net/L5p0ueqe/1/

2 个答案:

答案 0 :(得分:1)

Array.push()返回数组的长度。这是一个记录在案的功能。您正在成功推送到阵列。您只是没有成功console.log新值。当你console.log()时:

JSON.parse(this.categories[this.editingId - 1].addons).push({name:'', price:''}))

您将记录push()的返回值,而不是已推入的数组。

要解决此问题,您应该保存JSONA.parse()push,然后console.log的结果:

let addons = '[{"name":"Peppers","price":50},{"name":"Pepperoni","price":150},{"name":"Chicken","price":250},{"name":"Cheese","price":150},{"name":"Broccoli","price":100},{"name":"Corn","price":75},{"name":"Extra Sauce","price":250},{"name":"Extra Meat","price":350}]';

var parsed = JSON.parse(addons)
console.log('parsed ', parsed);

parsed.push({name:'Caviar', price:'10000'})

console.log('pushed ', parsed);

push()的一些文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

答案 1 :(得分:1)

var addonsJson = this.categories[this.editingId - 1].addons;
console.log('addons ', addonsJson);
var addons = JSON.parse(addonsJson);
console.log('parsed ', addons);
addons.push({name:'', price:''})
console.log('pushed ', addons);

您需要将数组存储在变量中,修改它,然后输出修改后的数组。