Toggle values into and out of an array in Javascript

前端 未结 4 944
臣服心动
臣服心动 2021-02-19 05:08

I want to have a simple array of values, ie

var simpleArray = [\"SE1\",\"SE2\",\"SE3\"];

I want to check this array when an action happens (a c

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-19 05:22

    Assuming the order of the items doesn't matter you can do something like this:

    function toggleArrayItem(a, v) {
        var i = a.indexOf(v);
        if (i === -1)
            a.push(v);
        else
            a.splice(i,1);
    }
    

    The .indexOf() method does work in IE from version 9 onwards, but if you need to support older IE versions you can use a shim as explained at MDN. Or if you're using jQuery anyway use $.inArray() instead.

提交回复
热议问题