How to create a clone of the next array, not a link?

Code (simple replacement cycle):

fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err

  data = data.split('\n\n')
  var tree = data

  for (var i = 0; i < tree.length; ++i) {
    if (tree[i].match(/^#/g)) {
      data[i] = data[i]
        .replace(/^#### (.*)/gm, '<h4>$1</h4>')
        .replace(/^### (.*)/gm, '<h3>$1</h3>')
        .replace(/^## (.*)/gm, '<h2>$1</h2>')
        .replace(/^# (.*)/gm, '<h1>$1</h1>')
    }
  }

  data = data.join('\n\n')
  tree = tree.join('\n\n')

  console.log(data)
  console.log(tree)

So, in this case, both dataand treehave the same conclusion:

<h1>Test</h1>

<h2>Test</h2>

Lorem "**ipsum?**" dolor 'sit!' amet

Anooo

* * *

"Ipsum?" "'**dolor**'" *sit!* amet, consetetur
eirmod tempor--invidunt **ut** labore

Anothes

What I want to do is keep the original value datain tree, so it datawill only change, but not tree.

How to do it?

tree should remain as follows:

# Test

## Test

Lorem "**ipsum?**" dolor 'sit!' amet

Anooo

* * *

"Ipsum?" "'**dolor**'" *sit!* amet, consetetur
eirmod tempor--invidunt **ut** labore

Anothes
+4
source share
3 answers

Use Array.prototype.slice () .

The slice() method returns a shallow copy of a portion of an array into a new array object.

var tree = data.slice();

+5
source

Use hack

var tree = data.slice(0)

It can be wrapped in a separate function / method.

+3
source

Jquery

var newObj = obj.extend({}, obj)

AngularJS

var newObj = angular.copy(obj)

javascript

JSON.parse(JSON.stringify(obj));
+2

All Articles