gpt4 book ai didi

javascript - 从 json 对象中删除 json 数组

转载 作者:行者123 更新时间:2023-11-28 19:27:11 24 4
gpt4 key购买 nike

在这里,我从 json 对象中删除特定的数组 [2]。但是,我在控制台中看到的是 -- 数组值被删除,但当我在删除后在 jquery 中使用 $.each 检查时,它仍然保留在 idx 中。那么,如何正确删除整个数组对象呢?

var obj = {
equipments:'first',
messages:['msg1','msg2','msg3'],
}

console.log(obj);
$.each(obj.messages, function (idx, obj) {
alert("before deleted index value" +idx);
});

obj1 = obj;

if(obj1["equipments"] == 'first' ) {
delete obj1.messages[2];
}

console.log(obj1);
$.each(obj1.messages, function (idx, obj1) {
alert("after deleted but index remains same" +idx);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

最佳答案

当您在数组上使用delete时,它不会删除该索引,而是将元素设置为undefined,但数组长度保持不变。

因此,您可以使用 splice() 但您还需要意识到,无论您对 obj1 执行什么操作,obj 也会发生这种情况,因为obj1 是对 obj 的引用。当您执行 obj1=obj

时,它不是副本

关于javascript - 从 json 对象中删除 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27631973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com