我正在使用一种方法来删除 JSON 中的特定行。用户按下一个按钮,该按钮确定要删除哪一行。我知道正在传入正确的索引,但我的问题是,当我尝试删除该行时,它只是将其替换为 null
,所以仍然有一些东西。如何完全删除它?
function removeTest(place) {
var parsedObject = JSON.parse(localStorage["flexuralStrengthSamples"]);
delete parsedObject[parseInt(place.data.text)];
localStorage["flexuralStrengthSamples"] = JSON.stringify(parsedObject);
console.log(JSON.stringify(parsedObject));
displaySamples();
}
以及我生成的 JSON:
[{"Result":"Fail","Method":"T97E-v1","Beam1":{"TestingMachineId":"1","BeamAge":"1","WidthUpper":1,"WidthCenter":1,"WidthLower":1,"WidthAverage":1,"DepthRight":1,"DepthCenter":1,"DepthLeft":1,"DepthAverage":1,"MaxLoad":1,"FS":18,"PSI":"18.00000","BreakOutside":"No"},"Beam2":{"BeamAge":"","WidthUpper":null,"WidthCenter":null,"WidthLower":null,"WidthAverage":null,"DepthRight":null,"DepthCenter":null,"DepthLeft":null,"DepthAverage":null,"MaxLoad":null,"FS":null,"PSI":"NaN"},"WaitForCuring":"No","AverageOfBeams":"NaN"},null]
在本例中,我尝试删除两个中的第二个。
最佳答案
根据生成的 JSON,您有一个 Objects {}
的 Array []
。
为了从 Array
中删除项目(并更新其长度
),您必须使用 splice
More reading on the delete
operator :
Deleting array elements
When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.
示例
var arr = [ {name: "Hello"}, {name: "World"} ];
// Delete does not modify an array's length, hence the "undefined"
delete arr[1]; // => [Object, undefined × 1]
// Splice will change the contents of an array and update its length
arr.splice(1,1); // => [Object]
关于jquery - 完全删除 JSON 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33135441/