The ability to perform a search is one of the key functions of any programming languages. We don’t have to look very fast, just take a look at Google, the most popular search engine in the world. Due to its exclusive and highly effective search algorithm, it commands a major portion of the search engine market, and hence the search advertising market. In fact, it captured more than 60% of the Internet advertising market!
26.2 Performing Linear Search
In this lesson, we will learn how to write a script to perform a linear search for an array that consists of integers. We employ the If operator to compare the search value entered by the user and each number in the array. If the search value is equal to the number concern, it will return the position of that number in the array (which is actually the value of the subscript plus 1, as the subscript of the array starts with 0). we need to use the function parseInt to convert the value of the subscript into a numeric value so that it can perform arithmetic operation. We also use the logical operators for and if to perform the search operation.
The following is the script:
Click Example 26.1 to view the actual output.