Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deep copy in javascript?

I have a situation similar to what you see below. The variable id is set to '03' before the first asynchronous callback is returned. Is there a way to deep copy, or "close" around the variable like you can with blocks in Objective-C? Is there a best practice?

var ids = ['01', '02', '03'];

for(var i=0, i < ids.length; i++){
  var id = ids[i];
  collection.find({id: ids} function () {
    console.log(id);
  });
}

The console output is:

03
03
03
like image 743
rob Avatar asked Mar 09 '26 01:03

rob


1 Answers

There are several ways to do it. One is to iterate with a a method that uses a closure as a callback.

ids.forEach(function (elem) {
    collection.find({id: ids} function () {
        console.log(elem);
    });
});
like image 160
Explosion Pills Avatar answered Mar 10 '26 14:03

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!