0

如果给定一个对象,例如:

  taste =
    0: "Hate"
    1: "Really Dislike"
    2: "Dislike"
    3: ""
    4: "Like"
    5: "Really Like"
    6: "Love"

我正在寻找一个函数,如果给定值,它将返回键。我尝试了以下

  Object::getKeyByVal = (value) ->
    for prop of this
      return prop  if this[prop] is value  if @hasOwnProperty(prop)

使用这个, alert time.getKeyByVal("< 1.5 hours") 将返回 8,但它给出的错误会杀死脚本的其余部分;

Uncaught TypeError: Object function (value) {
      var prop;
      for (prop in this) {
        if (this.hasOwnProperty(prop) ? this[prop] === value : void 0) {
          return prop;
        }
      }
    } has no method 'exec' 

有没有更好的方法来获取给定值的密钥?

4

1 回答 1

1

试试这个 :

getKeyFromValue = (obj,value)->
  for own k,v of obj
    if v==value
      return k

o =
  a:1
  b:2
  c:3
  d:4

console.log(getKeyFromValue(o,3)) # should output c

查看现场演示

于 2013-02-11T04:54:12.763 回答