【问题标题】:How do I create a clone of the following array rather than a reference? [duplicate]如何创建以下数组的克隆而不是引用? [复制]
【发布时间】:2015-03-24 13:45:43
【问题描述】:

代码(一个简单的替换循环):

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)

所以在这种情况下,datatree 具有相同的输出:

<h1>Test</h1>

<h2>Test</h2>

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

Anooo

* * *

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

Anothes

我想要做的是在tree 中保留data 的原始值,这样只有data 会发生变化,而tree 不会发生变化。

怎么做?

tree 应该保持这样:

# Test

## Test

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

Anooo

* * *

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

Anothes

【问题讨论】:

    标签: javascript


    【解决方案1】:

    使用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();

    【讨论】:

      【解决方案2】:

      使用技巧

      var tree = data.slice(0)
      

      它可以被包装到一个单独的函数/方法中。

      【讨论】:

      • data.slice() 可以在罗德里戈·阿西斯的回答中使用(不带参数)
      【解决方案3】:

      jQuery

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

      AngularJS

      var newObj = angular.copy(obj)
      

      纯javascript

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-06
        • 1970-01-01
        • 2013-11-23
        • 1970-01-01
        • 2017-06-20
        • 1970-01-01
        • 2021-06-12
        • 2016-02-06
        相关资源
        最近更新 更多