简体   繁体   English

Javascript array.push()不添加而是替换它

[英]Javascript array.push() do not add but replace it

I have some checkboxes styled with bootstrapSwitch . 我有一些用bootstrapSwitch样式的复选框。 I wrote a script that have to add value of checkbox to an array when bootstrapSwitch state is true. 我编写了一个脚本,当bootstrapSwitch state为true时,必须向数组添加复选框的值。

This is my code : 这是我的代码:

$('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)
});

But surprisingly push method replace the value and my s array always have one index. 但是令人惊讶的是push方法替换了值,并且我的s数组始终只有一个索引。

Would you please let me know why is that? 您能告诉我为什么吗?

Thanks in Advance 提前致谢

var s = new Array();

Define this out of the handler function. 在处理程序函数中定义它。

It's always 1 because you're recreating it everytime. 始终为1,因为您每次都在重新创建它。

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

so try this 所以试试这个

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)
});
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)
    });

Just declare the array outside. 只需在外部声明数组即可。 User [] instead on new Array() as it is faster. 用户[]代替了new Array(),因为它更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM