如果对象中存在值,则使用Javascript吗? [英] Javascript if a value exists in an object?

查看:63
本文介绍了如果对象中存在值,则使用Javascript吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个物体:

var car = {
    company: "Honda",
    year: "2011",
    Model: "Brio"
}

我想知道是否存在一个继承的方法(是正确的短语吗?)来检查给定对象内是否存在值,有点像x.hasOwnPropertyif (x in car).或者,我应该写我自己的东西.

I was wondering if there exists an inherited method (is that the right phrase?) to check if a value exists inside a given object, somewhat like x.hasOwnProperty, or if (x in car). Or, should I write my own.

我已经做了一些谷歌搜索,但是它们要么导致hasOwnProperty,要么检查数组中是否存在值.

I've done a few google searches, but they all either lead to hasOwnProperty or to check if a value exists inside an array.

编辑以使评论中的所有人满意: 我可以想到两种用例:

Editing to please all the people in the comments: There are two use cases i could think of where this would be useful:

  1. 检查未定义的键并报告哪个键

  1. checking for undefined keys and reporting which one

if (!car.isInvalid(car, undefined)) 
    validCarsArray.push (car);

  • 检查对象中是否存在常规用户输入

  • Checking if a general user input exists in an object

    var text = searchBox.input; 
    
    validCarArrays.forEach (function (car) {
        if (car.hasOwnValue(car, text)) {
        displayToUserAsResult (car);
        }
    });
    

  • 推荐答案

    否,没有内置的方法来搜索对象上的值.

    唯一的方法是遍历对象的所有键并检查每个值.使用即使在旧的浏览器中也可以使用的技术,您可以执行以下操作:

    The only way to do so is to iterate over all the keys of the object and check each value. Using techniques that would work even in old browsers, you can do this:

    function findValue(o, value) {
        for (var prop in o) {
            if (o.hasOwnProperty(prop) && o[prop] === value) {
                return prop;
            }
        }
        return null;
    }
    
    findValue(car, "2011");    // will return "year"
    findValue(car, "2012");    // will return null
    

    注意:即使可能存在多个匹配的属性,这也会返回包含搜索值的第一个属性.以效率为代价,您可以返回包含所需值的所有属性的数组.

    Note: This will return the first property that contains the search value even though there could be more than one property that matched. At the cost of efficiency, you could return an array of all properties that contain the desired value.

    注意:这使用额外的.hasOwnProperty()检查作为对任何向Object.prototype添加可枚举属性的代码的保护措施.如果没有这样的代码,并且您确定永远不会有,那么可以取消.hasOwnProperty()检查.

    Note: This uses the extra .hasOwnProperty() check as a safeguard against any code that adds enumerable properties to Object.prototype. If there is no such code and you're sure there never will be, then the .hasOwnProperty() check can be eliminated.

    这篇关于如果对象中存在值,则使用Javascript吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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