jquery 中不知道数组下标索引的情况下删除数组中的值

var arr=[];
这里用 arr.splice方法 添加或删除,替换数组中元素返回一个新的数组,此方法会改变原有数组的内容此方法中两个参数代表代表删除元素,
3个参数代表替换和添加元素如下:
var list = [];
list.push(1);
list.push(2);
list.push(3);
console.log(list); // [1, 2, 3]

// 删除
list.splice(0, 1);  // 删除  -> 从下标为0开始,长度为1
console.log(list); // [2,3]
list.splice(0, 2);  // 删除  -> 从下标为0开始,长度为2
console.log(list); // []

//替换
list.splice(0, 1, 4); // 替换 -> 从下标为0开始,长度为1的数组元素替换成4
console.log(list);  // [4,2,3]
list.splice(0, 2, 4); // 替换 -> 从下标为0开始,长度为2的数组元素替换成4(即4,2整体替换成4)
console.log(list);  // [4,3]

//添加
list.splice(1, 0, 5); // 表示在下标为1处添加一项5
console.log(list); // [1,5,2,3] 
list.splice(1,0,5,4,3); // 表示在下标为1处依次添加5/4/3三个元素
console.log(list); // [1,5,4,3,2,3]

此方法获取数组中指定的值在数组中的位置,$.inArray(value,arr) 如
arr = ['a','b','c','d'];

   arrays.splice($.inArray('c',arr),1);

   alert(arr);

结果: a,b,d;

综合案例,根据选中或取消checkbox中的值,向textbox中添加值

$(function () {          
            //用于向textbox赋值
            var txtValue = '';
            //存放选中或未选中checkbox的值
            var attr = [];
            //获取textbox中最后一个‘,’的索引
            var lastIndex = '';
           //给checkbox绑定单击事件
            $('.qusAnswer').click(function () {                              
              //如果为选中状态就向数组中添加选中状态的checkbox的值
                if ($(this).attr('checked')) {
                    txtValue = '';
                    attr.push($(this).val());
                  //循环数组给txtValue赋值
                  for (var i = 0; i < attr.length; i++) {
                      txtValue += attr[i]+',';
                  }
                  //把txtValue的值赋值给textbox
                  $('#engQuestion').val(txtValue);
                  //获取最后一个‘,’的索引
                  lastIndex = $('#engQuestion').val().lastIndexOf(',');
                  //得到最终结果赋值给textbox
                  $('#engQuestion').val($('#engQuestion').val().substring(0, lastIndex));

                }
                else {
                  //从数组中删除未选中的checkbox的值
                    attr.splice($.inArray($(this).val(), attr), 1);
                    txtValue = '';
                    for (var i = 0; i < attr.length; i++) {
                        txtValue += attr[i] + ',';
                    }
                      //把txtValue的值赋值给textbox
                    $('#engQuestion').val(txtValue);
                         //获取最后一个‘,’的索引
                    lastIndex = $('#engQuestion').val().lastIndexOf(',');
                       //得到最终结果赋值给textbox
                    $('#engQuestion').val($('#engQuestion').val().substring(0, lastIndex));
                }
            })
        })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值