关联阵列拼接不起作用 [英] Associate Array splice does not work
问题描述
我试图理解为什么在nodejs数组中拼接不能在关联数组上工作.
I am trying to understand why in nodejs array splice does not work on an associate array.
var a = [];
a['x1'] = 234234;
a['x2'] = 565464;
console.log("Init-------");
showIt();
a.splice(0, 1);
console.log("After splice-------");
showIt();
delete a['x1'];
console.log("After delete-------");
showIt();
function showIt(){
var keys = Object.keys(a);
var len = keys.length;
var i=0;
while (i < len) {
console.log( ' ' + i + ' ------------ ' + keys[i] );
i++;
}
}
结果:
Init-------
0 ------------ x1
1 ------------ x2
After splice-------
0 ------------ x1
1 ------------ x2
After delete-------
0 ------------ x2
拼接数组无济于事...
Splicing the array does nothing...
浏览器中的结果相同...
Same results in a browser...
将数组定义为以下参数时,拼接工作正常:
Splice works as expected when the array is defined as:
var a = ['x1','x2','x3'];
console.log("Init-------");
console.log(a);
a.splice('x1', 1);
console.log("After splice-------");
console.log(a);
就像在第一个示例中一样,该数组被视为好像在第二个中被定义为对象{}
一样,它被视为一个数组.
Looks like in the first example, the array is being treated as if is was defined as a object {}
in the 2nd, it's being treated more like an array.
这实际上不是关于备用阵列的问题,它更多地是关于一个阵列的问题,该阵列从0开始并在几天内连续增长到1000万.随着阵列的增长,阵列中的数据将被删除,以便一次在阵列中存储大约1000个项目.
This is not really a question about spare arrays, it is more of a question of an array which is starting at 0 and growing sequentially to 10 million over a period of days. As it is growing the array is being deleted from so that around 1000 items are in the array at one time.
我正在考虑通过使用非数字键或将其定义为对象{}
来强制使用哈希表,以便其作用类似于稀疏数组.
I am considering forcing the use of hash tables by using non-numeric keys or defining as a object {}
so that the it acts like a sparse array.
最后,我不确定这是否重要...
In the end, I am not sure if it matters...
推荐答案
在JavaScript中,没有关联数组之类的东西-数组(如其他语言的普通数组)和对象(如其他语言的assoc数组)语言).在您的示例中,a
是普通数组,但是您在其上设置了非数字键,因此普通数组方法(例如splice)看不到它.它们仅在0...a.length
范围内.
In JavaScript there is no such thing as an associative array -- there are arrays (like normal arrays in other languages) and objects (like assoc. arrays in other languages). In your example a
is a normal array but you set non-numerical keys on it, so the normal array methods (like splice) do not see it. They only look in the range 0...a.length
.
制作a
对象无济于事;无法拼接对象.尝试仅使用数字键([1]
而不是['x1']
).
Making a
an object won't help; it is not possible to splice an object. Try using only numerical keys ([1]
instead of ['x1']
).
这篇关于关联阵列拼接不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!