JavaScript array_replace
!No description available for array_replace. @php.js developers: Please update the function summary text file.
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 | function array_replace (arr) { // + original by: Brett Zamir (http://brett-zamir.me) // * example 1: array_replace(["orange", "banana", "apple", "raspberry"], {0 : "pineapple", 4 : "cherry"}, {0:"grape"}); // * returns 1: {0: 'grape', 1: 'banana', 2: 'apple', 3: 'raspberry', 4: 'cherry'} if (arguments.length < 2) { throw new Error('There should be at least 2 arguments passed to array_replace()'); } // Although docs state that the arguments are passed in by reference, it seems they are not altered, but rather the copy that is returned (just guessing), so we make a copy here, instead of acting on arr itself var retObj = {}; for (var prop in arr) { retObj[prop] = arr[prop]; } for (var i = 1; i < arguments.length; i++) { for (var p in arguments[i]) { retObj[p] = arguments[i][p]; } } return retObj; } |
Examples
Running
1 | array_replace(["orange", "banana", "apple", "raspberry"], {0 : "pineapple", 4 : "cherry"}, {0:"grape"}); |
Should return
1 | {0: 'grape', 1: 'banana', 2: 'apple', 3: 'raspberry', 4: 'cherry'} |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have array_replace goodness in JavaScript.
No comments yet. Be the first!
spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: @HalfWinter, Paulo Freitas, Andros Peña Romo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>