在给定对象属性值的JavaScript中,我可以找到相应的属性名吗?

时间:2011-12-13 20:46:56

标签: javascript object

我将一个配置对象与每个幻灯片的名称传递给一个实例化jQuery工具可滚动的函数。我希望位置栏中的URL与活动标签ID匹配。我有它的工作,以便传递名称为in的URL将导航到正确的幻灯片(位于提供的代码的底部),但我试图在幻灯片更改时获取URL更新。我知道我需要做什么才能得到它,但不知道怎么做,就像问题标题一样..将值传递给对象并获取具有该值的属性。

$(function () {
    Scrollablenav.init({
        "#tulips": 0,
        "#daffodils": 1,
        "#zebras": 2,
        "#horseshoes": 3
    });
});

Scrollablenav.init = function(config){
    var scroller = $(".scrollable").scrollable({
        circular: true,
        onSeek: function (event) {
            parent.location.hash = function(){
            //something that looks at config, sends it the value of the current slide and returns corresponding property name
            }
        }
    }).navigator({
            navi: '#slideTabs',
            naviItem: 'a',
            activeClass: 'current',
            history: true
    }).data('scrollable');

    if (!isNaN(config[location.hash])){
        scroller.seekTo(config[location.hash], 0);
     }
}

3 个答案:

答案 0 :(得分:4)

您可以创建自己的功能,根据其值找到属性名称:

function findPropertyName(object, property_value, strict) {
    if (typeof strict=='undefined'){
        strict = false;
    };
    for (property in object){
        if ((strict && object[property] === property_value) ||
            (!strict && object[property] == property_value)){
            return property;
        }
    }
    return false;
}

功能描述:

  • 它将返回具有给定值的第一个属性的名称,如果没有找到此属性,则返回false
  • 第三个参数负责确定是否应该进行严格比较(例如,字符串“123”等于整数123 - 就像在'123'==123中一样,但不是 相同 - 如'123'===123)。
  • 可以改进函数以返回具有给定值的所有属性,但我认为您不需要它。

要查看功能,请参阅this jsfiddle

答案 1 :(得分:2)

这样的东西?

function getMyHash(config, value) {
  for (item in config) {
    if (config[item] === value) {
      return item;
    }
  }
};

基本上你必须迭代和匹配值;你不能按价值查找。

答案 2 :(得分:0)

您可以更改配置的格式吗?换句话说,我们可以这样做:

$(function () {
    Scrollablenav.init({
        "#tulips": { Key: 'tulips', Index: 0 },
        "#daffodils": { Key: 'daffodils', Index: 1 },
        "#zebras": { Key: 'zebras', Index: 2 },
        "#horseshoes": { Key: 'horseshoes', Index: 3 }
    });
});

如果这不起作用,您可以在某处将索引映射回密钥的新对象:

var keys = {
   1: 'tulips',
   2: 'daffodils',
   3: 'zebras',
   4: 'horseshoes',
};

<强>更新

您也可以动态构建此配置:

$(function () {
    var values = ['#tulips', '#daffodils', '#zebras', '#horseshoes'];
    var config = {};

    for(var i = 0; i < values.length; i++)
    {
       config[values[i]] = { Index: i, Key: values[i] };
    }

    Scrollablenav.init(config);
});