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