[英]JavaScript: Better solution than delete
I have the following array: 我有以下数组:
var example = [
function() { /* hello */ },
function() { /* goodbye */ }
];
I use delete example[0];
我用
delete example[0];
and am left with the following result: 并留下以下结果:
var example = [
1: function() { /* goodbye */ }
];
Is there a better solution than delete
? 有比
delete
更好的解决方案吗? Or is there a simple way to fix the indexes in the array? 或者有一种简单的方法来修复数组中的索引? (I have jQuery at my disposal)
(我有jQuery可供我使用)
Edit : I fixed the example array. 编辑 :我修复了示例数组。 The indexes were there for the example.
索引就是这样的例子。
As example
is an array, instead of delete
, you can use .splice
[MDN] : example
是一个数组,而不是delete
,你可以使用.splice
[MDN] :
example.splice(0, 1);
But if examples
is actually an object, you'd have to use delete
and iterate over all properties and "rename" them. 但是,如果
examples
实际上是一个对象,则必须使用delete
并迭代所有属性并“重命名”它们。 Though it's probably easier to use an array instead. 虽然使用数组可能更容易。
The reason why you get this result with delete
is that you are removing the property '0'
from the underlying object and the property '1'
still exists. 您通过
delete
获得此结果的原因是您要从基础对象中删除属性'0'
,并且属性'1'
仍然存在。 You are basically operating on a lower level. 你基本上是在较低的水平上运作。
Another problem with gaps in the indexes is that array.length
will always return the the highest index + 1 and not the actual number of values in the array. 索引中存在间隙的另一个问题是
array.length
将始终返回最高索引+ 1而不是数组中实际的值数。 So after deleting the element, example.length
would still be 2
. 因此删除元素后,
example.length
仍为2
。
Your way of defining an array is wrong. 你定义数组的方法是错误的。 This is how its done:
这就是它的完成方式:
var example = [
function() { /* hello */ },
function() { /* goodbye */ }
];
you can use shift to remove the first element: 你可以使用shift来删除第一个元素:
var firstElement = example.shift();
You could use a custom sort function: 您可以使用自定义排序功能:
array.sort(sortfunction)
function sortfunction(a, b){
// check indexes here
}
You can just shift your first element. 你可以改变你的第一个元素。
http://jsfiddle.net/4zW7B/1/ http://jsfiddle.net/4zW7B/1/
var example = [
function() { alert('hello'); },
function() { alert('goodbye'); }
];
example[0]();
example.shift();
example[0]();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.