Skip to content

Instantly share code, notes, and snippets.

@fael
Created September 12, 2011 21:03
Show Gist options
  • Save fael/1212419 to your computer and use it in GitHub Desktop.
Save fael/1212419 to your computer and use it in GitHub Desktop.
Some Array Functions
in_array = function(needle, haystack, argStrict) {
// Checks if the given value exists in the array
var found = false,
key, strict = !! argStrict;
for (key in haystack) {
if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
found = true;
break;
}
}
return found;
}
/* http://phpjs.org/ */
array_push = function(array) {
// Pushes elements onto the end of the array
var i, argv = arguments,
argc = argv.length;
for (i = 1; i < argc; i++) {
array[array.length++] = argv[i];
}
return array.length;
}
/* http://phpjs.org/ */
array_shift = function(array) {
// Pops an element off the beginning of the array
if (array.length > 0) {
return array.shift();
}
return null;
}
array_pop = function(array) {
// Pops an element off the end of the array
var key = '',
cnt = 0;
if (array.hasOwnProperty('length')) {
// Indexed
if (!array.length) {
// Done popping, are we?
return null;
}
return array.pop();
} else {
// Associative
for (key in array) {
cnt++;
}
if (cnt) {
delete (array[key]);
return array[key];
} else {
return null;
}
}
}
array_unshift = function(array) {
// Pushes elements onto the beginning of the array
var argc = arguments.length,
argv = arguments,
i;
for (i = 1; i < argc; i++) {
array.unshift(argv[i]);
}
return (array.length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment