我似乎无法解决为什么拼接在这种情况下无法正常工作。
我已经阅读了无数堆栈溢出的拼接示例,我似乎无法看到问题。
此代码基本上应该从JSON数组中的第一项(并且仅)中删除索引14。
var product_variations = JSON.parse('[{"0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[],"12":"","13":"","14":"Red","15":"Small"}]');
product_variations[0].splice(14, 1);
答案 0 :(得分:5)
它不起作用,因为splice
是数组上可用的方法,而不是对象。
这是一个对象:
{"0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[],"12":"","13":"","14":"Red","15":"Small"}
实际上你会收到如下错误:
TypeError:undefined不是函数(评估' product_variations [0] .splice(14,1)')
您可以使用delete
代替或将其转换为数组:
delete product_variations[0]["14"]
要将其转换为数组,您可以尝试:
function objectToArray(p){
var keys = Object.keys(p);
keys.sort(function(a, b) {
return a - b;
});
var arr = [];
for (var i = 0; i < keys.length; i++) {
arr.push(p[keys[i]]);
}
return arr;
}
var product_variations = JSON.parse('[{"0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[],"12":"","13":"","14":"Red","15":"Small"}]');
var arr = objectToArray(product_variations[0]);
arr.splice(14, 1);
答案 1 :(得分:3)
使用&#34;删除&#34; Javascript中的关键字。
delete myArray["lastname"];
如上所述,它不起作用,因为你的对象只是一个列表而你正在使用的是一个对象(assoc数组)
<强> .splice 强>
splice()方法在数组中添加/删除项目,并返回已删除的项目。
注意:此方法会更改原始数组。
删除强>
删除操作符从对象中删除属性。
所以你的代码应该是
delete product_variations[0]["14"]
请记住,14号码是一个字符串,而不是一个数字,正如您在代码中所写的那样,因为它是数组中元素的名称。
尽管如此,在看到您正在管理的代码之后,我强烈建议您将其切换到列表,因为关键字只是普通列表的索引(除了它们从1开始)