循环遍历javascript对象,但从中间开始

Looping through an javascript object literal but start in the middle

本文关键字:中间 开始 遍历 javascript 对象 循环      更新时间:2023-09-26

我正在寻找一种方法来循环通过一个对象,但开始例如在中间的一些地方或任何其他值,例如:Tue, Wen, Thu, Fri, Sat, Sun, Mon而不是Sun, Mon, Tue, Wen, Thu, Fri, Sat(如在示例中使用的对象)。

//基本周概述

daysByName = {
    sunday    : 'Sun', 
    monday    : 'Mon', 
    tuesday   : 'Tue', 
    wednesday : 'Wed', 
    thursday  : 'Thu', 
    friday    : 'Fri', 
    saturday  : 'Sat'
}

//基本循环

for (var key in daysByName) {
    console.log(daysByName[key]);
}

不能依赖对象中属性的顺序,结果可能取决于浏览器(例如属性按字母顺序重新排序)。你不能依靠……为了单独捕获属性,您需要添加一个hasOwnProperties()过滤器。

你有两个选择:

  • 使用数组代替对象

    daysByName = [{周日:"太阳"},{周一:"星期一"},...)

  • 在对象本身中输入索引:

    周日:{缩写:"太阳",指数:0}

您可以尝试这样做,其中startIndex是您想要开始的startIndex

daysByName = {
    sunday    : 'Sun', 
    monday    : 'Mon', 
    tuesday   : 'Tue', 
    wednesday : 'Wed', 
    thursday  : 'Thu', 
    friday    : 'Fri', 
    saturday  : 'Sat'
}
// Obtain object length
var keys = [];
for (var key in daysByName) {
    keys.push(key)
}
// Define start index
var startIndex = 4, count = 0;
for (var key in daysByName) {
    // Index is made by the count (what you normally do) + the index. Module the max length of the object.
    console.log(daysByName[ keys[ (count + startIndex) % (keys.length)] ]);
    count++; // Don't forget to increase count.
}

这里有一个小提琴:http://jsfiddle.net/MH7JJ/2/