2

What is the equivalents of php functions push_array and in_array in javascript?

Arrays are simple (not multidimensional).

Haven't found something native.

3 Answers 3

4

You're looking for the push method and the indexOf method.

Note that indexOf is not supported by IE, so you'll need to implement it yourself, like this:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n) // shortcut for verifying if it's NaN
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}

(copied from MDC)

Sign up to request clarification or add additional context in comments.

Comments

2

push_array:

This is native to the Array object in JavaScript:

var someArray = [];
someArray.push(value);

in_array:

This is not native to the Array in JavaScript however some browsers have support for Array.indexOf which can be compared to -1. If that is not supported than you need to iterate over the items.

function inArray(elem, array) {
    if (array.indexOf) {
        return array.indexOf(elem) > -1;
    }

    for (var i = 0, length = array.length; i < length; i++) {
        if (array[ i ] === elem ) {
            return true;
        }
    }

    return false;
}

Comments

1

You have to be using the JavaScript Array object. Then you can use .push().

For find: How do I check if an array includes an object in JavaScript?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.