Is There a JavaScript Equivalent of PHP's in_array()?

Susan Sarandon
Release: 2024-11-13 06:16:02
Original
420 people have browsed it

Is There a JavaScript Equivalent of PHP's in_array()?

Can JavaScript Mimic PHP's in_array() Functionality?

In PHP, in_array() compares a value to those within an array, returning true if a match is found. JavaScript lacks a direct equivalent, but community-developed libraries provide analogous functionality.

Instance Matching Using jQuery or Prototype

jQuery's inArray and Prototype's Array.indexOf tackle this challenge by iteratively comparing values:

// jQuery implementation:
function inArray(needle, haystack) {
  for (var i = 0; i < haystack.length; i++) {
    if (haystack[i] == needle) return true;
  }
  return false;
}
Copy after login

Array Comparison

For more complex scenarios, where you need to compare entire arrays, a custom function can fulfill this need:

function arrayCompare(a1, a2) {
  if (a1.length != a2.length) return false;
  for (var i = 0; i < a1.length; i++) {
    if (a1[i] !== a2[i]) return false;
  }
  return true;
}

function inArray(needle, haystack) {
  for (var i = 0; i < haystack.length; i++) {
    if (typeof haystack[i] == 'object') {
      if (arrayCompare(haystack[i], needle)) return true;
    } else {
      if (haystack[i] == needle) return true;
    }
  }
  return false;
}
Copy after login

Usage

// Test the custom function:
var a = [['p', 'h'], ['p', 'r'], 'o'];
if (inArray(['p', 'h'], a)) {
  console.log('ph was found');
}
if (inArray(['f', 'i'], a)) {
  console.log('fi was found');
}
if (inArray('o', a)) {
  console.log('o was found');
}
Copy after login

The above is the detailed content of Is There a JavaScript Equivalent of PHP's in_array()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template