在Javascript中将值切换到数组中和从数组中切换出来 [英] Toggle values into and out of an array in Javascript

查看:66
本文介绍了在Javascript中将值切换到数组中和从数组中切换出来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个简单的数组,即

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 click on a google map layer), that will pass a value to this function and either add the value to the array, or remove it from the array if it already exists.

我现在感到有点困惑看到.splice / push / inArray / indexOf(在IE中不起作用)/ grep(jQuery) - 不确定最佳做法是什么。

I am now just a bit confused having seen .splice/push/inArray/indexOf (that doesn't work in IE)/grep (jQuery) - not sure what the best practice is.

推荐答案

假设项目的顺序无关紧要,你可以这样做:

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

.indexOf()方法从IE 9开始在IE中工作,但是如果您需要支持旧的IE版本,可以使用垫片,如 MDN 。或者如果您正在使用jQuery,请使用 $。inArray() 而不是。

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.

这篇关于在Javascript中将值切换到数组中和从数组中切换出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆