[英]Why does this JavaScript array return undefined?
Can someone explain when I run this file using node why one value is returning as undefined and the other is not included in the list. 有人可以解释当我使用节点运行此文件时,为什么一个值返回的是未定义值,而另一个值未包括在列表中。
3 David 3大卫
var queue = {}; queue[0] = 'Cam'; queue[1] = 'Doug'; queue[2] = 'Caleb'; queue[3] = 'David'; queue[4] = 'Kelli'; queue[5] = 'Aparna'; var sorted_keys = Object.keys(queue).sort(); for (var key in sorted_keys) { console.log(key + " " + queue[key]); } for (var key in sorted_keys) { if (key == 2 || key == 4) { // trying to mock disable accounts and remove delete queue[key]; } } sorted_keys = Object.keys(queue).sort(); for (var key in sorted_keys) { console.log(key + " " + queue[key]); }
Your main issue is that you're iterating sorted_keys
which is an array of keys and you're trying to use the index value from the array to index into the queue
object, but that's the array index, not the key into the queue
object. 您的主要问题是,您要迭代
sorted_keys
这是键的数组),并且尝试使用数组中的索引值索引到queue
对象中,但这是数组索引,而不是queue
对象中的键。 You need to get the actual value from the array, not the index from the array because that's where the key into the queue
object is. 您需要从数组中获取实际值,而不是数组中的索引,因为这是
queue
对象的关键所在。
You also shouldn't be iterating arrays at all with for/in
, though that isn't what is actually causing the problem. 您也不应该使用
for/in
来迭代数组,尽管这实际上并不是导致问题的原因。
If you change your last iteration to this, you will see what you expect: 如果将最后一次迭代更改为此,您将看到期望的结果:
for (i = 0; i < sorted_keys.length; i++) {
key = sorted_keys[i];
console.log(key + " " + queue[key]);
}
Working demo: http://jsfiddle.net/jfriend00/5dPsR/ 工作演示: http : //jsfiddle.net/jfriend00/5dPsR/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.