javascript - 优化Javascript方法来填充或清空数组

标签 javascript jquery arrays optimization

我想知道是否有更好的方法来向数组添加/删除复选框值。遗憾的是我无法使用 ECMAScript 5 indexOf() 因为我需要支持 IE8/7。

这是一个有效的 jsfiddle 示例:http://jsfiddle.net/puyQr/

这个方法的作用是:

/**
 * If a user clicks onto the checkbox, the value of the value attribute is
 * only added to the array when the value not yet exists. However, if
 * the value already exists, the value is removed.
 */

var values = [];
jQuery(':checkbox').on('click', function(){     
    var index = jQuery.inArray(this.value, values);
    if(index === -1) {
        values.push(this.value);
    } else {
        values.splice(index, 1);
    }
});

最佳答案

从复选框获取值的另一种方法:

var values = jQuery(':checkbox:checked').map(function(){
    return $(this).val();
}).get();

demo

关于javascript - 优化Javascript方法来填充或清空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14280442/

相关文章:

javascript - 在 Three.js 中旋转相机无法正常工作

c# - 如何维护在 Web 表单上输入/选择的数据而不保存它

python : Calculate the eucledean distances from one coordinates to a array with coordinates

javascript - 什么情况下使用context?

javascript - PostMessage 读取 Iframe 内容

javascript - 需要从表单中获取选定的选项值并通过 jquery/javascript 传回

javascript - 创建数组的副本,但仅包含特定字段

c++ - 在 C++ 中返回结构数组

javascript - 如何从字符串中删除所有空格,除非该字符串的一部分被 Node 中的特定字符包围?

javascript - $.add 和 $.append JQuery 有什么区别