我可以通过相反的顺序循环javascript对象吗? [英] Can I loop through a javascript object in reverse order?

查看:134
本文介绍了我可以通过相反的顺序循环javascript对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个这样的JavaScript对象:

  foo = {
one:some ,
two:thing,
three:else
};

我可以这样循环:

<$ p (foo.hasOwnProperty(i)){
//做某事
}
$($ f $) b $ b

它将以的顺序循环访问一个 3 > 2 > 一个



问题:对象反转功能。如果是一个数组,我可以使用 unshift 来反向或构建一个新数组,但是当我需要反向循环时,属性。任何想法?



谢谢!

解决方案

Javascript对象没有保证的固有顺序,所以不存在反向顺序。


4.3.3对象对象是Object类型的成员。它是属性的一个无序集合,每个属性都包含一个原始
值,对象或函数。存储在
对象的属性中的函数称为方法。

浏览器似乎返回他们被添加到对象相同的顺序,但由于这不是标准的,你可能不应该依赖这种行为。

一个简单的函数调用每个函数属性和浏览器for..in给出的顺序是相反的:

  // f是一个函数, obj作为'this'和属性名称作为第一个参数
函数reverseForIn(obj,f){
var arr = [];
(var key in obj){
//如果需要,添加hasOwnPropertyCheck
arr.push(key);

for(var i = arr.length-1; i> = 0; i--){
f.call(obj,arr [i]);


$ b // usage
reverseForIn(obj,function(key){console.log('KEY:',key,'VALUE:这[key]);});

使用JsBin: http://jsbin.com/aPoBAbE/1/edit

我再次说for..in的顺序是不能保证的,所以相反的顺序是不能保证的。谨慎使用!


So I have a JavaScript object like this:

foo = {
  "one": "some",
  "two": "thing",
  "three": "else"
};

I can loop this like:

for (var i in foo) {
  if (foo.hasOwnProperty(i)) {
    // do something
  }
}

Which will loop through the properties in the order of one > two > three.

However sometimes I need to go through in reverse order, so I would like to do the same loop, but three > two > one.

Question:
Is there an "object-reverse" function. If it was an Array, I could reverse or build a new array with unshift but I'm lost with what to do with an object, when I need to reverse-loop it's properties. Any ideas?

Thanks!

解决方案

Javascript objects don't have a guaranteed inherent order, so there doesn't exist a "reverse" order.

4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

Browsers do seem to return the properties in the same order they were added to the object, but since this is not standard, you probably shouldn't rely on this behavior.

A simple function that calls a function for each property in reverse order as that given by the browser's for..in, is this:

// f is a function that has the obj as 'this' and the property name as first parameter
function reverseForIn(obj, f) {
  var arr = [];
  for (var key in obj) {
    // add hasOwnPropertyCheck if needed
    arr.push(key);
  }
  for (var i=arr.length-1; i>=0; i--) {
    f.call(obj, arr[i]);
  }
}

//usage
reverseForIn(obj, function(key){ console.log('KEY:', key, 'VALUE:', this[key]); });

Working JsBin: http://jsbin.com/aPoBAbE/1/edit

Again i say that the order of for..in is not guaranteed, so the reverse order is not guaranteed. Use with caution!

这篇关于我可以通过相反的顺序循环javascript对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆