简体   繁体   English

在javascript对象中,获取值属性的最佳方法是什么?

[英]in a javascript object, what's best way to get the attribute of a value?

if we have a javascript object 如果我们有一个javascript对象

var calories = { apple:200, pear:280, banana:300, peach:325 }

what is best way to find the (first) fruit that has 280 calories? 查找(含)280卡路里水果的最佳方法是什么?

could Object.getOwnPropertyNames(calories).forEach... but there should be a better way. 可以Object.getOwnPropertyNames(calories).forEach...但应该有更好的方法。

For example, I was thinking of Array.prototype.indexOf() which does the same thing for an Array. 例如,我在想Array.prototype.indexOf() ,它对Array做同样的事情。

Caution! 警告! There is no guarantee that all browsers return the same result. 不能保证所有浏览器都返回相同的结果。 In fact they don't. 实际上他们没有。

For example: 例如:

var x = { a: 1, b: 1 };
delete x.a;
x.a = 1;

What should x.indexOf(1) return here? x.indexOf(1)应该在这里返回什么? b or a ? b还是a Turns out IE does property enumeration differently than other browsers, and the specs say that's perfectly fine. 事实证明,IE进行的属性枚举与其他浏览器不同,规范说的还不错。 So IE would return a while other browsers would return b . 因此,IE将返回a而其他浏览器将返回b

You can verify that by calling 您可以通过致电验证

Object.getOwnPropertyNames(x); // IE: a,b - other browsers: b,a
Object.keys(x); // same
for (var i in x) { console.log(i); } // same

Obviously, the problem here is that there's no notion of "order" on object indices because, well, that's what objects are: unordered maps. 显然,这里的问题是对象索引上没有“顺序”的概念,因为对象就是:无序映射。

but there should be a better way 但是应该有更好的方法

No, there really shouldn't. 不,真的不应该。 The way 99% of all use cases go, developers are more interested in getting the value from the key. 所有用例中有99%都用这种方式,开发人员对从密钥中获取价值更感兴趣。

Linear search using for..in construct: 使用for..in构造的线性搜索:

var fruit = null;

for (var prop in calories) {

  if (calories[prop] == 280) {

    fruit = prop;
    break;
  }
}

You could extend the prototype of Object doing this: 您可以这样做扩展对象的原型:

// Returns one key (any) of the value if it exists, or undefined if not
Object.defineProperty(Object.prototype, "keyOf", { 
    value: function(value) {
        for (var key in this) if (this[key] == value) return key;
        return undefined;
    }
});

Using this way instead of the common Object.prototype.keyOf = ... will work with jQuery if you use it. 如果您使用jQuery,则可以使用这种方式代替常见的Object.prototype.keyOf = ...来使用jQuery。

And then you could use it like this: 然后您可以像这样使用它:

var myArray = {...};
var index = myArray.keyOf(value);

It will also work with normal arrays: [...] , so you could use it instead of indexOf too. 它也可用于普通数组: [...] ,因此您也可以使用它代替indexOf

Remember to use the triple-character operators to check if it's undefined: 请记住使用三字符运算符来检查它是否未定义:

index === undefined // to check the value/index exists    
index !== undefined // to check the value/index does not exist

Of course you could change the name of the function if you prefer and remember not to declare any variable called 'undefined'. 当然,如果您愿意并且可以记住不要声明任何称为“未定义”的变量,则可以更改函数的名称。

Remember also that as indexOf, it will return at most one key defined but it could be more than one possible, so in that case you will need something like this ( .keysOf(...) ): 还要记住,作为indexOf,它最多返回定义的一个键,但可能会返回多个键,因此在这种情况下,您将需要这样的内容( .keysOf(...) ):

// Returns all the keys of the value if it exists (an empty array if not)
Object.defineProperty(Object.prototype, "keysOf", { 
    value: function(value) {
        var allKeys = [];
        for (var key in this) if (this[key] == value) allKeys.push(key);
        return allKeys;
    }
});

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

相关问题 在JS中获取元元素的属性值的最佳方法是什么? - What is the best way to get a Meta Element's Attribute Value in JS? 更改javascript对象数组中的对象属性的最佳方法是什么? - what's the best way to change an object property in a javascript object array? 如果对象可能未定义,则检查JavaScript对象值的最佳方法 - Best way to check JavaScript object's value if object may be undefined 在JavaScript中不变地更新对象某些属性的最佳方法是什么? - What's the best way to update some properties of an object immutably in JavaScript? 将对象属性链接到值的最佳方法是什么? - What's the best way to keep an object property linked to a value? 按特定值对 JSON 对象进行分组的最佳方法是什么? - What's the best way to group a JSON object by a certain value? 消除JavaScript列表中重复项的最佳方法是什么? - What's the best way to get rid of duplicates in a JavaScript list? 从对象获取实体的最佳方法是什么? - What's the best way to get entities from a object? 在 JavaScript 中获取日期值以在 MongoDB 中发送的最佳方法是什么? - What is The Best way to get date value in JavaScript to send in MongoDB.? 使用JavaScript获取和设置单个cookie值的“最佳”方法是什么? - What is the “best” way to get and set a single cookie value using JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM