JavaScript数组的push()方法不是添加而是替换。

6

我有一些用bootstrapSwitch样式的复选框。

我写了一个脚本,在bootstrapSwitch的状态为true时,将复选框的值添加到数组中。

以下是我的代码:

$('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) - Rayon
2
这是因为你在每次点击时重新创建了s。尝试将s的声明移到事件回调之外。 - haim770
3个回答

6
var s = new Array();

将此定义放在处理程序函数之外。

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


1
我真不好意思... :-)... 网站允许的话,我会尽快接受你的答案。 - Kiyarash
有时候会发生这种情况 :) 谢谢! - Alok Patel

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

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接