Javascript Array Concat不能正常工作。为什么? [英] Javascript Array Concat not working. Why?

查看:156
本文介绍了Javascript Array Concat不能正常工作。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创建了这个jqueryui小部件。它创建了一个div,我可以将错误输入。小部件代码如下所示:

So I've created this jqueryui widget. Its creates a div that I can stream errors into. The widget code looks like this:

$.widget('ui.miniErrorLog', {
   logStart: "<ul>",   // these next 4 elements are actually a bunch more complicated.
   logEnd:   "</ul>",
   errStart: "<li>",
   errEnd:   "</li>",
   content:  "",
   refs:     [],

   _create: function() { $(this.element).addClass( "ui-state-error" ).hide(); },

   clear: function() { 
      this.content = ""; 
      for ( var i in this.refs )
         $( this.refs[i] ).removeClass( "ui-state-error" );
      this.refs = [];
      $(this.element).empty().hide(); 
   }, 

   addError: function( msg, ref ) {
      this.content += this.errStart + msg + this.errEnd; 
      if ( ref ) {
         if ( ref instanceof Array )
            this.refs.concat( ref );
         else
            this.refs.push( ref );
         for ( var i in this.refs )
            $( this.refs[i] ).addClass( "ui-state-error" );
      }
      $(this.element).html( this.logStart + this.content + this.logEnd ).show();
   }, 

   hasError: function()
   {
      if ( this.refs.length )
         return true;
      return false;
   },
});

我可以在其中添加错误消息,并引用将进入错误状态的页面元素。我用它来验证对话框。在addError方法中,我可以传入一个id或一组id,如下所示:

I can add error messages into it, and references to page elements that is will put into an error state. I use it to validate dialogs. In the "addError" method I can pass in a single id, or an array of ids, like this:

$( "#registerDialogError" ).miniErrorLog( 
   'addError', 
   "Your passwords don't match.", 
   [ "#registerDialogPassword1", "#registerDialogPassword2" ] );

但是当我传入一个id的数组时,它不起作用。问题在于以下几行(我认为):

But when I pass in an array of id's it doesn't work. The problem is in the following lines (i think):

if ( ref instanceof Array )
   this.refs.concat( ref );
else
   this.refs.push( ref );

为什么连接不起作用。 this.refs和ref都是数组。那么为什么concat不起作用?

Why doesn't that concat work. this.refs and ref are both arrays. So why doesn't the concat work?

奖励:我在这个小部件中做了什么其他的蠢事吗?这是我的第一个。

Bonus: am I doing anything else dumb in this widget? It's my first one.

推荐答案

concat方法不会更改原始数组,需要重新分配。

The concat method doesn't change the original array, you need to reassign it.

if ( ref instanceof Array )
   this.refs = this.refs.concat( ref );
else
   this.refs.push( ref );

这篇关于Javascript Array Concat不能正常工作。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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