简体   繁体   English

循环遍历从索引开始的对象

[英]Loop through an object starting at an index

I have an object that is a list of chatrooms, where the keys are chat room names and the value is a reference to the chat room.我有一个对象,它是一个聊天室列表,其中键是聊天室名称,值是对聊天室的引用。 I want to deliver the rooms to users 50 rooms at a time.我想一次向用户提供 50 个房间。 But I don't see how this can be done with an object.但我不知道如何用一个对象来做到这一点。

Suppose you want to loop through假设你想循环

var obj = {
   "a" : 1,
   "b" : 2.
   "c" : 3
}

But start at "b", ending up with only "b" and "c" being accessed.但是从“b”开始,最后只访问“b”和“c”。 Can it be done, including using some kind of map or table?可以做到吗,包括使用某种地图或表格?

You shouldn't rely on objects keys to be sorted.您不应该依赖对象键进行排序。 Although most browsers (if not all) keep them sorted.尽管大多数浏览器(如果不是全部)都会对它们进行排序。

So if you want to trust browsers, you can add a counter variable and start doing stuff after the counter reached whatever you want.因此,如果您想信任浏览器,您可以添加一个计数器变量,并在计数器达到您想要的任何值后开始执行操作。 You can get the length of your object using Object.keys() (returns an array).您可以使用Object.keys()获取对象的长度(返回一个数组)。 Mixing both, you can do this:混合两者,你可以这样做:

var object = {
    a: 1,
    b: 2,
    c: 3
};

var keys = Object.keys(object);
var counter;

for (counter = 0; counter < keys.length; counter++) {
    if (counter < 1) continue; // Skip until the second element
    console.log(object[keys[counter]]);
}

If you don't know the position of the key in advance, you can add a flag variable and activate it when you reach the desired key, like this:如果您事先不知道钥匙的位置,您可以添加一个标志变量并在您到达所需的钥匙时激活它,如下所示:

var keys = Object.keys(object);
var counter;
var start = false;

for (counter = 0; counter < keys.length; counter++) {
    if (keys[counter] === 'b') start = true;
    if (!start) continue;
    console.log(object[keys[counter]]);
}

Please see the MDN post regarding the for...in loop:请参阅有关for...in循环的 MDN 帖子:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Basically, you have no guarantee as to the order in which the keys inside the object will be iterated over.基本上,您无法保证对象内的键将被迭代的顺序。 So the idea of skipping a certain "index" simply doesn't apply.所以跳过某个“索引”的想法根本不适用。 I think you need to follow the advice in the comments, and either keep an array of those keys you are interested in, or figure out a way to quickly exclude certain keys as they come up in your loop.我认为您需要遵循评论中的建议,要么保留一组您感兴趣的键,要么想办法快速排除某些键,因为它们出现在您的循环中。

try this way试试这个方法

var obj = {
   'a' : 1,
   'b' : 2.
   'c' : 3
};
var ignoreItems = ['a'];

for (var key in obj) {
  if (ignoreItems.indexOf(key) === -1) {
    // ADD YOUR CODE HERE
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM