UNPKG

phpjs

Version:

php.js offers community built php functions in javascript

87 lines (76 loc) 2.79 kB
--- layout: page title: "JavaScript array_push function" comments: true sharing: true footer: true alias: - /functions/view/array_push:331 - /functions/view/array_push - /functions/view/331 - /functions/array_push:331 - /functions/331 --- <!-- Generated by Rakefile:build --> A JavaScript equivalent of PHP's array_push {% codeblock array/array_push.js lang:js https://raw.github.com/kvz/phpjs/master/functions/array/array_push.js raw on github %} function array_push (inputArr) { // From: http://phpjs.org/functions // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // % note 1: Note also that IE retains information about property position even // % note 1: after being supposedly deleted, so if you delete properties and then // % note 1: add back properties with the same keys (including numeric) that had // % note 1: been deleted, the order will be as before; thus, this function is not // % note 1: really recommended with associative arrays (objects) in IE environments // * example 1: array_push(['kevin','van'], 'zonneveld'); // * returns 1: 3 var i = 0, pr = '', argv = arguments, argc = argv.length, allDigits = /^\d$/, size = 0, highestIdx = 0, len = 0; if (inputArr.hasOwnProperty('length')) { for (i = 1; i < argc; i++) { inputArr[inputArr.length] = argv[i]; } return inputArr.length; } // Associative (object) for (pr in inputArr) { if (inputArr.hasOwnProperty(pr)) { ++len; if (pr.search(allDigits) !== -1) { size = parseInt(pr, 10); highestIdx = size > highestIdx ? size : highestIdx; } } } for (i = 1; i < argc; i++) { inputArr[++highestIdx] = argv[i]; } return len + i - 1; } {% endcodeblock %} - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/array/array_push.js) Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest match to this hashtable-like data structure. Please also note that php.js offers community built functions and goes by the [McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just: - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/array/array_push.js) ### Example 1 This code {% codeblock lang:js example %} array_push(['kevin','van'], 'zonneveld'); {% endcodeblock %} Should return {% codeblock lang:js returns %} 3 {% endcodeblock %} ### Other PHP functions in the array extension {% render_partial _includes/custom/array.html %}