0

我正在寻找一种遍历对象的方法,但例如从中间的某个位置或任何其他值开始,例如: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]);
}
4

2 回答 2

0

您不能依赖对象中属性的顺序,结果可能取决于浏览器(例如按字母顺序重新排序的属性)。而且您不能仅依靠 for...in 来捕获属性,您需要添加一个 hasOwnProperties() 过滤器。

您有两种选择:

  • 使用数组而不是对象

    daysByName = [ {星期日:'星期日'},{星期一:'星期一'},...]

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

    星期日:{缩写:“Sun”,索引:0}

于 2013-01-19T20:50:20.050 回答
-1

您可以尝试这样的事情,其中​​ 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/

于 2013-01-19T20:22:16.567 回答