Sunday, May 19, 2024
55
rated 0 times [  61] [ 6]  / answers: 1 / hits: 17052  / 12 Years ago, sun, april 22, 2012, 12:00:00

I've the following piece of code for copying one associative array to other,


<script>

var some_db = new Array();

some_db["One"] = "1";

some_db["Two"] = "2";

some_db["Three"] = "3";

var copy_db = new Array();

alert(some_db["One"]);

copy_db = some_db.slice();

alert(copy_db["One"]);

</script>

But the second alert says "undefined".. Am I doing something wrong here? Any pointers please...


More From » associative-array

 Answers
15

In JavaScript, associative arrays are called objects.


<script>
var some_db = {
"One" : "1",
"Two" : "2",
"Three" : "3"
};

var copy_db = clone(some_db);

alert(some_db["One"]);

alert(copy_db["One"]);

function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
</script>

I would normally use var copy_db = $.extend({}, some_db); if I was using jQuery.


Fiddle Proof: http://jsfiddle.net/RNF5T/


Thanks @maja.


[#86068] Saturday, April 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jimmieo

Total Points: 515
Total Questions: 102
Total Answers: 110

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;