【问题标题】:Javascript array.push() do not add but replace itJavascript array.push() 不添加而是替换它
【发布时间】:2016-04-18 10:04:33
【问题描述】:

我有一些带有bootstrapSwitch 样式的复选框。 我编写了一个脚本,当 bootstrapSwitch state 为真时,必须将复选框的值添加到数组中。

这是我的代码:

$('input[name^=skill]').on('switchChange.bootstrapSwitch', function (event, state) {

    //alert(state);
    //var s = [];

    var s = new Array();

    if( state === true )
    {
        //var value = $(this).val();
        s.push( $(this).val() );

        console.log(s);//(value)

    }

        console.log(s);//(value)
});

但令人惊讶的是push 方法替换了值,而我的s 数组总是有一个索引。

请告诉我这是为什么?

在此先感谢

【问题讨论】:

  • 从处理程序中定义数组..或者每次调用处理程序时它将被初始化为[](empty-array)...
  • 那是因为您在每次点击时重新创建s。尝试将s 的声明移到事件回调之外

标签: javascript arrays bootstrap-switch


【解决方案1】:
var s = new Array();

在处理函数之外定义它。

它始终为 1,因为您每次都在重新创建它。

【讨论】:

  • 真丢脸... :-)... 只要网站允许我这样做,我就会接受您的回答
  • 有时会发生 :) 谢谢!
【解决方案2】:
var s = new Array();// this line should be out side of function. so it will not be new object everytime

试试这个

var s = new Array();// this line should be here. so it will not be new object everytime

$('input[name^=skill]').on('switchChange.bootstrapSwitch', function (event, state) {

    //alert(state);
    //var s = [];

    var s = new Array();

    if( state === true )
    {
        //var value = $(this).val();
        s.push( $(this).val() );

        console.log(s);//(value)

    }

        console.log(s);//(value)
});

【讨论】:

    【解决方案3】:
    var s = [];
    
    $('input[name^=skill]').on('switchChange.bootstrapSwitch', function (event, state) {
    
            //alert(state);
            //var s = [];
    
    
    
            if( state === true )
            {
                //var value = $(this).val();
                s.push( $(this).val() );
    
                console.log(s);//(value)
    
            }
    
                console.log(s);//(value)
        });
    

    只需在外面声明数组。用户 [] 而不是 new Array() 因为它更快。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-29
      • 2019-11-15
      • 1970-01-01
      • 2015-02-05
      • 2012-08-21
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      相关资源
      最近更新 更多