【问题标题】:Fetch the value of a property passed to method as a paremeter in jQuery获取传递给方法的属性值作为jQuery中的参数
【发布时间】:2015-01-23 15:17:30
【问题描述】:

我想要一个抽象方法根据我作为参数传递给方法的属性名来读取json对象的属性。

我认为举个例子更容易解释。

假设我有以下 json 对象:

var coll =
[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]

function GetPropertyValue(collection, index, property_name)
{
    :
    :
}

在哪里

GetPropertyValue(coll, 0, 'firstName');

返回“约翰”,而

GetPropertyValue(coll, 0, 'lastName');

返回“Doe,并且

GetPropertyValue(coll, 2, 'lastName');

返回“琼斯

问候。

【问题讨论】:

    标签: jquery object properties parameter-passing


    【解决方案1】:

    这很简单。你拥有一切。只需使用括号符号组装它。顺便说一句,我将“G”做得很小,以符合 javascript 广泛接受的命名约定。

    function getPropertyValue(collection, index, property_name) {
        return collection[index][property_name]; 
    }
    

    【讨论】:

    • 'property_name' 是一个“字符串”,不能在对象之前,因为它是一个特定的现有属性。我错了吗?
    • @user3021830 很高兴为您提供帮助 :)
    【解决方案2】:

    我会扩展 Amit Joki 的答案以包括一些检查以确保查询甚至可以返回。可能是这样的:

    function getPropertyValue(collection, index, property_name) {
                if(collection[index].hasOwnProperty(property_name)){
                    return collection[index][property_name]; 
                }else{
                    //do something here id the property is not there
                }
    
            }
    

    代码有点多,但您必须处理这些问题,当您无法直接控制对象本身时更是如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-05
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 2012-12-12
      • 1970-01-01
      • 2019-07-30
      相关资源
      最近更新 更多