Home > Backend Development > PHP Tutorial > How to Achieve PHP's `in_array()` Functionality in JavaScript?

How to Achieve PHP's `in_array()` Functionality in JavaScript?

Barbara Streisand
Release: 2024-11-17 04:28:03
Original
539 people have browsed it

How to Achieve PHP's `in_array()` Functionality in JavaScript?

JavaScript Alternative to PHP's in_array()

In JavaScript, there is no built-in function that behaves exactly like PHP's in_array(). However, popular libraries offer utility functions to achieve similar functionality.

jQuery's inArray function follows PHP's behavior and compares values within arrays:

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

If you need to check if an array is within another array, like PHP's in_array(), a custom function like the following is needed:

function inArrayNested(needle, haystack) {
  var length = haystack.length;
  for (var i = 0; i < 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

This function inArrayNested checks both simple and nested arrays. Remember that extending the Array prototype is generally not recommended.

The above is the detailed content of How to Achieve PHP's `in_array()` Functionality in JavaScript?. 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