最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Array search in javascript - Stack Overflow

programmeradmin0浏览0评论

I have an array in javascript and a variable as follows:

var numArr = ["one", "two", "three"];
var searchNum = "four";

I want to search "four" in numArr and if not present then execute some statements... as in

if (searchNum not in numArr)
{
    // do this
}

Does javascript have any function which could search in any array and return true or false without me writing a whole lot of search code.

I have an array in javascript and a variable as follows:

var numArr = ["one", "two", "three"];
var searchNum = "four";

I want to search "four" in numArr and if not present then execute some statements... as in

if (searchNum not in numArr)
{
    // do this
}

Does javascript have any function which could search in any array and return true or false without me writing a whole lot of search code.

Share Improve this question asked Jan 4, 2013 at 19:27 tech_humantech_human 7,16617 gold badges75 silver badges134 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Use indexOf:

if ( numArr.indexOf(searchNum) > -1 ) {

} else {}

The method will return -1 if it fails to find searchNum. Otherwise it will return the index at which it found it.

You can also use:

var result = [];
    for(i=0;i<listdata.names.length;i++){
        var n = listdata.names[i].toLocaleLowerCase();
        var s = x('input').value.toLocaleLowerCase();
        if(n.indexOf(s) != -1){result.push(listdata.names[i]);}
    }

This way we can output an result from an input value and existing array of values.

Little typicall to understand but..... :)

发布评论

评论列表(0)

  1. 暂无评论