在数组中搜索元素 [英] search for element within an array

查看:115
本文介绍了在数组中搜索元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的data[l][m]包含1,2,3,4,5 我正在尝试搜索一个特定的数字,在其中说"2".有更好的方法吗?

My data[l][m] contains 1,2,3,4,5 I'm trying to search for a particular number, say '2' in it. Is there a better way to do this?

for (var n = 0; n < data[l][m].length; n++) {
    if(data[l][m][n] == num){ // num is equal to '2'
        number = data[l][0];
        document.form.options[l-1] = new Option(number,number,true,true);
    }
}

以及以下内容如何:['id1',['a',[1,2,3,4,5]],['b',[3,4,5,6,7]]]
预先非常感谢.

And how about in: ['id1',['a',[1,2,3,4,5]],['b',[3,4,5,6,7]]]
Many thanks in advance.

推荐答案

如果您已经包含jQuery,请使用

If you're already including jQuery, use $.inArray(), like this:

if($.inArray(num, data[l][m]) > -1) {
  number = data[l][0];
  document.form.options[l-1] = new Option(number,number,true,true);
}

较短的原始JS版本是直接的 .indexOf() 在Array上,但是IE默认情况下没有此功能.

The shorter vanilla JS version is a direct .indexOf() on the Array, but IE doesn't have this by default.

这篇关于在数组中搜索元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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