Suppose I have this code:
假设我有这个代码:
var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;
Now if I wanted to remove "lastname"?....is there some equivalent ofmyArray["lastname"].remove()
?
现在如果我想删除“姓”? ....是否有一些等价的myArray["lastname"].remove()?
(I need the element gone because the number of elements is important and I want to keep things clean.)
(我需要去掉元素,因为元素的数量很重要,我想保持事物的整洁。)
14 个解决方案
#1
974
Use the "delete" keyword in Javascript.
在Javascript中使用“delete”关键字。
delete myArray["lastname"];
EDIT:
编辑:
In some JavaScript engine, the delete keyword might hurt performance as it will undo compile / JIT optimization.
在一些JavaScript引擎中,delete关键字可能会损害性能,因为它将撤消编译/ JIT优化。
http://www.html5rocks.com/en/tutorials/speed/v8/ http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/
http://www.html5rocks.com/en/tutorials/speed/v8/ http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/
#2
70
All objects in JavaScript are implemented as hashtables/associative arrays. So, the following are the equivalent:
JavaScript中的所有对象都实现为散列表/关联数组。因此,以下是等价的:
alert(myObj["SomeProperty"]);
alert(myObj.SomeProperty);
And, as already indicated, you "remove" a property from an object via the delete
keyword, which you can use in two ways:
如前所述,您可以通过delete关键字从对象中“删除”属性,您可以使用以下两种方式:
delete myObj["SomeProperty"];
delete myObj.SomeProperty;
Hope the extra info helps...
希望这些额外的信息能有所帮助……
#3
38
None of the previous answers address the fact that Javascript does not have associative arrays to begin with - there is no array
type as such, see typeof
.
前面的回答都没有提到Javascript一开始就没有关联数组这一事实——没有数组类型,请参见typeof。
What Javascript has, are object instances with dynamic properties. When properties are confused with elements of an Array object instance then Bad Things™ are bound to happen:
Javascript拥有的是具有动态属性的对象实例。当属性是困惑的元素数组对象实例然后坏事™注定会发生:
Problem
var elements = new Array()
elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]
console.log("number of elements: ", elements.length) // returns 2
delete elements[1]
console.log("number of elements: ", elements.length) // returns 2 (?!)
for (var i = 0; i < elements.length; i++)
{
// uh-oh... throws a TypeError when i == 1
elements[i].onmouseover = function () { window.alert("Over It.")}
console.log("success at index: ", i)
}
Solution
To have a universal removal function that does not blow up on you, use:
要有一个通用的去除功能,不会对你产生影响,使用:
Object.prototype.removeItem = function (key) {
if (!this.hasOwnProperty(key))
return
if (isNaN(parseInt(key)) || !(this instanceof Array))
delete this[key]
else
this.splice(key, 1)
};
//
// Code sample.
//
var elements = new Array()
elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]
console.log(elements.length) // returns 2
elements.removeItem("prop")
elements.removeItem(0)
console.log(elements.hasOwnProperty("prop")) // returns false as it should
console.log(elements.length) // returns 1 as it should
#4
22
That only removes deletes the object but still keeps the array length same.
这只删除删除对象,但仍然保持数组长度不变。
To remove you need to do something like:
要删除,您需要做以下事情:
array.splice(index, 1);
#5
13
While the accepted answer is correct, it is missing the explanation why it works.
虽然公认的答案是正确的,但它却没有解释它为什么有效。
First of all, your code should reflect the fact that this is NOT an array:
首先,您的代码应该反映这不是一个数组的事实:
var myObject = new Object();
myObject["firstname"] = "Bob";
myObject["lastname"] = "Smith";
myObject["age"] = 25;
Note that all objects (including Array
s) can be used this way. However, do not expect for standard JS array functions (pop, push,...) to work on objects!
注意,所有对象(包括数组)都可以这样使用。但是,不要期望标准的JS数组函数(pop, push,…)在对象上工作!
As said in accepted answer, you can then use delete
to remove the entries from objects:
如“已接受答案”中所述,您可以使用delete从对象中删除条目:
delete myObject["lastname"]
You should decide which route you wish to take - either use objects (associative arrays / dictionaries) or use arrays (maps). Never mix the two of them.
您应该决定要走哪条路—使用对象(关联数组/字典)或使用数组(映射)。不要把两者混淆。
#6
7
Use method splice
to completely remove item from an object array:
使用方法splice从对象数组中完全删除项:
Object.prototype.removeItem = function (key, value) {
if (value == undefined)
return;
for (var i in this) {
if (this[i][key] == value) {
this.splice(i, 1);
}
}
};
var collection = [
{ id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
{ id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
{ id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];
collection.removeItem("id", "87353080-8f49-46b9-9281-162a41ddb8df");
#7
5
You are using Object, you are not having an associative array to begin with. With an associative array, adding and removing items goes like this:
你正在使用对象,你没有一个关联数组。使用关联数组,添加和删除条目如下所示:
Array.prototype.contains = function(obj)
{
var i = this.length;
while (i--)
{
if (this[i] === obj)
{
return true;
}
}
return false;
}
Array.prototype.add = function(key, value)
{
if(this.contains(key))
this[key] = value;
else
{
this.push(key);
this[key] = value;
}
}
Array.prototype.remove = function(key)
{
for(var i = 0; i < this.length; ++i)
{
if(this[i] == key)
{
this.splice(i, 1);
return;
}
}
}
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function ForwardAndHideVariables() {
var dictParameters = getUrlVars();
dictParameters.add("mno", "pqr");
dictParameters.add("mno", "stfu");
dictParameters.remove("mno");
for(var i = 0; i < dictParameters.length; i++)
{
var key = dictParameters[i];
var value = dictParameters[key];
alert(key + "=" + value);
}
// And now forward with HTTP-POST
aa_post_to_url("Default.aspx", dictParameters);
}
function aa_post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
//move the submit function to another variable
//so that it doesn't get written over if a parameter name is 'submit'
form._submit_function_ = form.submit;
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var i = 0; i < params.length; i++)
{
var key = params[i];
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form._submit_function_(); //call the renamed function
}
#8
5
As other answers have noted, what you are using is not a Javascript array, but a Javascript object, which works almost like an associative array in other languages except that all keys are converted to strings. The new Map stores keys as their original type.
正如其他答案所指出的,您使用的不是一个Javascript数组,而是一个Javascript对象,它的工作方式与其他语言中的关联数组几乎一样,只是所有的键都被转换为字符串。新的映射将密钥存储为原始类型。
If you had an array and not an object, you could use the array's .filter function, to return a new array without the item you want removed:
如果你有一个数组而不是一个对象,你可以使用数组的.filter函数返回一个新的数组,而不需要删除你想要的项:
var myArray = ['Bob', 'Smith', 25];
myArray = myArray.filter(function(item) {
return item !== 'Smith';
});
If you have an older browser and jQuery, jQuery has a $.grep
method that works similarly:
如果您有一个较老的浏览器和jQuery, jQuery有一个$。类似工作的grep方法:
myArray = $.grep(myArray, function(item) {
return item !== 'Smith';
});
#9
3
You can remove an entry from your map by explicitly assigning it to 'undefined'. As in your case:
可以通过显式地将条目赋值为“undefined”,从映射中删除条目。在你的情况中:
myArray["lastname"] = undefined;
myArray(“姓”)=定义;
#10
2
If for whatever reason the delete key is not working (like it wasnt working for me )
如果出于某种原因,删除键不起作用(就像它对我不起作用一样)
You can splice it out and then filter the undefined values
您可以将它拼接出来,然后过滤未定义的值
// to cut out one element via arr.splice(indexToRemove, numberToRemove);
array.splice(key, 1)
array.filter(function(n){return n});
Dont try and chain them since splice returns removed elements;
不要试图将它们链起来,因为拼接返回删除的元素;
#11
2
Its very straight forward if you have underscore.js dependency in your project -
如果你有下划线,它是非常直接的。项目中的js依赖项
_.omit(myArray, "lastname")
#12
2
We can use it as a function too. Angular throws some error if used as a prototype. Thanks @HarpyWar. It helped me solve a problem.
我们也可以用它作为函数。如果作为原型,角会抛出一些错误。谢谢@HarpyWar。它帮我解决了一个问题。
var removeItem = function (object, key, value) {
if (value == undefined)
return;
for (var i in object) {
if (object[i][key] == value) {
object.splice(i, 1);
}
}
};
var collection = [
{ id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
{ id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
{ id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];
removeItem(collection, "id", "87353080-8f49-46b9-9281-162a41ddb8df");
#13
1
By using the "delete"
keyword, it will delete the array element from array in javascript.
通过使用“delete”关键字,它将在javascript中从数组中删除数组元素。
For example,
例如,
Consider following statements.
考虑下面的语句。
var arrayElementToDelete = new Object();
arrayElementToDelete["id"] = "XERTYB00G1";
arrayElementToDelete["first_name"] = "Employee_one";
arrayElementToDelete["status"] = "Active";
delete arrayElementToDelete["status"];
Last line of the code will remove the array element who's key is "status" from the array.
代码的最后一行将从数组中移除键为“status”的数组元素。
#14
0
var myArray = newmyArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;
var s = JSON.stringify(myArray);
s.replace(/"lastname[^,}]+,/g,'');
newmyArray = JSON.parse(p);
Without looping/iterates we get the same result
没有循环/迭代,我们会得到相同的结果
#1
974
Use the "delete" keyword in Javascript.
在Javascript中使用“delete”关键字。
delete myArray["lastname"];
EDIT:
编辑:
In some JavaScript engine, the delete keyword might hurt performance as it will undo compile / JIT optimization.
在一些JavaScript引擎中,delete关键字可能会损害性能,因为它将撤消编译/ JIT优化。
http://www.html5rocks.com/en/tutorials/speed/v8/ http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/
http://www.html5rocks.com/en/tutorials/speed/v8/ http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/
#2
70
All objects in JavaScript are implemented as hashtables/associative arrays. So, the following are the equivalent:
JavaScript中的所有对象都实现为散列表/关联数组。因此,以下是等价的:
alert(myObj["SomeProperty"]);
alert(myObj.SomeProperty);
And, as already indicated, you "remove" a property from an object via the delete
keyword, which you can use in two ways:
如前所述,您可以通过delete关键字从对象中“删除”属性,您可以使用以下两种方式:
delete myObj["SomeProperty"];
delete myObj.SomeProperty;
Hope the extra info helps...
希望这些额外的信息能有所帮助……
#3
38
None of the previous answers address the fact that Javascript does not have associative arrays to begin with - there is no array
type as such, see typeof
.
前面的回答都没有提到Javascript一开始就没有关联数组这一事实——没有数组类型,请参见typeof。
What Javascript has, are object instances with dynamic properties. When properties are confused with elements of an Array object instance then Bad Things™ are bound to happen:
Javascript拥有的是具有动态属性的对象实例。当属性是困惑的元素数组对象实例然后坏事™注定会发生:
Problem
var elements = new Array()
elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]
console.log("number of elements: ", elements.length) // returns 2
delete elements[1]
console.log("number of elements: ", elements.length) // returns 2 (?!)
for (var i = 0; i < elements.length; i++)
{
// uh-oh... throws a TypeError when i == 1
elements[i].onmouseover = function () { window.alert("Over It.")}
console.log("success at index: ", i)
}
Solution
To have a universal removal function that does not blow up on you, use:
要有一个通用的去除功能,不会对你产生影响,使用:
Object.prototype.removeItem = function (key) {
if (!this.hasOwnProperty(key))
return
if (isNaN(parseInt(key)) || !(this instanceof Array))
delete this[key]
else
this.splice(key, 1)
};
//
// Code sample.
//
var elements = new Array()
elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]
console.log(elements.length) // returns 2
elements.removeItem("prop")
elements.removeItem(0)
console.log(elements.hasOwnProperty("prop")) // returns false as it should
console.log(elements.length) // returns 1 as it should
#4
22
That only removes deletes the object but still keeps the array length same.
这只删除删除对象,但仍然保持数组长度不变。
To remove you need to do something like:
要删除,您需要做以下事情:
array.splice(index, 1);
#5
13
While the accepted answer is correct, it is missing the explanation why it works.
虽然公认的答案是正确的,但它却没有解释它为什么有效。
First of all, your code should reflect the fact that this is NOT an array:
首先,您的代码应该反映这不是一个数组的事实:
var myObject = new Object();
myObject["firstname"] = "Bob";
myObject["lastname"] = "Smith";
myObject["age"] = 25;
Note that all objects (including Array
s) can be used this way. However, do not expect for standard JS array functions (pop, push,...) to work on objects!
注意,所有对象(包括数组)都可以这样使用。但是,不要期望标准的JS数组函数(pop, push,…)在对象上工作!
As said in accepted answer, you can then use delete
to remove the entries from objects:
如“已接受答案”中所述,您可以使用delete从对象中删除条目:
delete myObject["lastname"]
You should decide which route you wish to take - either use objects (associative arrays / dictionaries) or use arrays (maps). Never mix the two of them.
您应该决定要走哪条路—使用对象(关联数组/字典)或使用数组(映射)。不要把两者混淆。
#6
7
Use method splice
to completely remove item from an object array:
使用方法splice从对象数组中完全删除项:
Object.prototype.removeItem = function (key, value) {
if (value == undefined)
return;
for (var i in this) {
if (this[i][key] == value) {
this.splice(i, 1);
}
}
};
var collection = [
{ id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
{ id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
{ id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];
collection.removeItem("id", "87353080-8f49-46b9-9281-162a41ddb8df");
#7
5
You are using Object, you are not having an associative array to begin with. With an associative array, adding and removing items goes like this:
你正在使用对象,你没有一个关联数组。使用关联数组,添加和删除条目如下所示:
Array.prototype.contains = function(obj)
{
var i = this.length;
while (i--)
{
if (this[i] === obj)
{
return true;
}
}
return false;
}
Array.prototype.add = function(key, value)
{
if(this.contains(key))
this[key] = value;
else
{
this.push(key);
this[key] = value;
}
}
Array.prototype.remove = function(key)
{
for(var i = 0; i < this.length; ++i)
{
if(this[i] == key)
{
this.splice(i, 1);
return;
}
}
}
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function ForwardAndHideVariables() {
var dictParameters = getUrlVars();
dictParameters.add("mno", "pqr");
dictParameters.add("mno", "stfu");
dictParameters.remove("mno");
for(var i = 0; i < dictParameters.length; i++)
{
var key = dictParameters[i];
var value = dictParameters[key];
alert(key + "=" + value);
}
// And now forward with HTTP-POST
aa_post_to_url("Default.aspx", dictParameters);
}
function aa_post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
//move the submit function to another variable
//so that it doesn't get written over if a parameter name is 'submit'
form._submit_function_ = form.submit;
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var i = 0; i < params.length; i++)
{
var key = params[i];
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form._submit_function_(); //call the renamed function
}
#8
5
As other answers have noted, what you are using is not a Javascript array, but a Javascript object, which works almost like an associative array in other languages except that all keys are converted to strings. The new Map stores keys as their original type.
正如其他答案所指出的,您使用的不是一个Javascript数组,而是一个Javascript对象,它的工作方式与其他语言中的关联数组几乎一样,只是所有的键都被转换为字符串。新的映射将密钥存储为原始类型。
If you had an array and not an object, you could use the array's .filter function, to return a new array without the item you want removed:
如果你有一个数组而不是一个对象,你可以使用数组的.filter函数返回一个新的数组,而不需要删除你想要的项:
var myArray = ['Bob', 'Smith', 25];
myArray = myArray.filter(function(item) {
return item !== 'Smith';
});
If you have an older browser and jQuery, jQuery has a $.grep
method that works similarly:
如果您有一个较老的浏览器和jQuery, jQuery有一个$。类似工作的grep方法:
myArray = $.grep(myArray, function(item) {
return item !== 'Smith';
});
#9
3
You can remove an entry from your map by explicitly assigning it to 'undefined'. As in your case:
可以通过显式地将条目赋值为“undefined”,从映射中删除条目。在你的情况中:
myArray["lastname"] = undefined;
myArray(“姓”)=定义;
#10
2
If for whatever reason the delete key is not working (like it wasnt working for me )
如果出于某种原因,删除键不起作用(就像它对我不起作用一样)
You can splice it out and then filter the undefined values
您可以将它拼接出来,然后过滤未定义的值
// to cut out one element via arr.splice(indexToRemove, numberToRemove);
array.splice(key, 1)
array.filter(function(n){return n});
Dont try and chain them since splice returns removed elements;
不要试图将它们链起来,因为拼接返回删除的元素;
#11
2
Its very straight forward if you have underscore.js dependency in your project -
如果你有下划线,它是非常直接的。项目中的js依赖项
_.omit(myArray, "lastname")
#12
2
We can use it as a function too. Angular throws some error if used as a prototype. Thanks @HarpyWar. It helped me solve a problem.
我们也可以用它作为函数。如果作为原型,角会抛出一些错误。谢谢@HarpyWar。它帮我解决了一个问题。
var removeItem = function (object, key, value) {
if (value == undefined)
return;
for (var i in object) {
if (object[i][key] == value) {
object.splice(i, 1);
}
}
};
var collection = [
{ id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
{ id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
{ id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];
removeItem(collection, "id", "87353080-8f49-46b9-9281-162a41ddb8df");
#13
1
By using the "delete"
keyword, it will delete the array element from array in javascript.
通过使用“delete”关键字,它将在javascript中从数组中删除数组元素。
For example,
例如,
Consider following statements.
考虑下面的语句。
var arrayElementToDelete = new Object();
arrayElementToDelete["id"] = "XERTYB00G1";
arrayElementToDelete["first_name"] = "Employee_one";
arrayElementToDelete["status"] = "Active";
delete arrayElementToDelete["status"];
Last line of the code will remove the array element who's key is "status" from the array.
代码的最后一行将从数组中移除键为“status”的数组元素。
#14
0
var myArray = newmyArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;
var s = JSON.stringify(myArray);
s.replace(/"lastname[^,}]+,/g,'');
newmyArray = JSON.parse(p);
Without looping/iterates we get the same result
没有循环/迭代,我们会得到相同的结果