如何删除键 + 值从哈希在 javascript

给予

var myHash = new Array();
myHash['key1'] = { Name: 'Object 1' };
myHash['key2'] = { Name: 'Object 2' };
myHash['key3'] = { Name: 'Object 3' };

如何从散列中删除 key2object 2,使其最终处于与我所做的相同的状态:

var myHash = new Array();
myHash['key1'] = { Name: 'Object 1' };
myHash['key3'] = { Name: 'Object 3' };

删除不是我想要的;

delete myHash['key2']

给了我这个:

var myHash = new Array();
myHash['key1'] = { Name: 'Object 1' };
myhash['key2'] = null;
myHash['key3'] = { Name: 'Object 3' };

我能找到的关于 spliceslice的唯一文档处理整数索引器,我没有。

编辑: 我也不知道“ key2”是否必须在位置[1]

更新

好吧,稍微转移一下注意力 delete 在表面上看起来确实是我想要的但是,我使用 json2.js 将我的对象字符串化为 json 以便推回到服务器,

删除之后,myHash 会被序列化为:

[ { Name: 'Object 1' }, null, { Name: 'Object 3' } ]

这是 json2.js 里的一个 bug 吗? 还是我删除的时候做错了什么?

谢谢

112276 次浏览

You're looking for delete:

delete myhash['key2']

See the Core Javascript Guide

Another option may be this John Resig remove method. can better fit what you need. if you know the index in the array.

Why do you use new Array(); for hash? You need to use new Object() instead.

And i think you will get what you want.

You say you don't necessarily know that 'key2' is in position [1]. Well, it's not. Position 1 would be occupied by myHash[1].

You're abusing JavaScript arrays, which (like functions) allow key/value hashes. Even though JavaScript allows it, it does not give you facilities to deal with it, as a language designed for associative arrays would. JavaScript's array methods work with the numbered properties only.

The first thing you should do is switch to objects rather than arrays. You don't have a good reason to use an array here rather than an object, so don't do it. If you want to use an array, just number the elements and give up on the idea of hashes. The intent of an array is to hold information which can be indexed into numerically.

You can, of course, put a hash (object) into an array if you like.

myhash[1]={"key1","brightOrangeMonkey"};