【问题标题】:Array.each outputs all methodsArray.each 输出所有方法
【发布时间】:2009-11-24 16:38:42
【问题描述】:

为什么会...

for(var k in this.errors) {
        $('error_list').insert({
            bottom: new Element('li').update(k + ' :'+this.errors[k])
        })
    }

...输出把所有的 Prototype 可枚举的方法,加上我添加到数组中的东西?

我正在构建一个关联数组:

this.errors['email'] = 'Your email is invalid';

【问题讨论】:

  • JavaScript 没有真正的关联数组。您正在设置数组的属性(这是合法的),但 JavaScript 没有用于这种用法的特殊方法。为此目的,最好使用对象而不是数组。

标签: javascript arrays prototype


【解决方案1】:

您可以使用 hasOwnProperty 来防止这种情况发生:

for(var k in this.errors) {
    if (this.errors.hasOwnProperty(k)) {
        $('error_list').insert({
            bottom: new Element('li').update(k + ' :'+this.errors[k])
        })
    }
}

【讨论】:

    【解决方案2】:

    你需要使用“hasOwnProperty”来防范。

    【讨论】:

      【解决方案3】:

      试试这个:

      $H(this.errors).each(function(error) {
          $('error_list').insert({
              bottom: new Element('li').update(error.key + ': ' + error.value)
          })
      })
      

      【讨论】:

        猜你喜欢
        • 2013-02-13
        • 1970-01-01
        • 2016-06-07
        • 2016-08-30
        • 2011-08-07
        • 2012-04-03
        • 2017-01-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多