【问题标题】:Array is being mutated when using slice() [duplicate]使用 slice() 时数组正在发生变异 [重复]
【发布时间】:2017-08-04 10:49:14
【问题描述】:
Array.prototype.indicesOf = function (el) {
    let indices = [];
    for (var i = this.length - 1; i >= 0; i--) {
        if (this[i] === el)
          indices.unshift(i);
    }
    return indices;
}

class CommentNester {

  constructor(comments) {
    this.comments = comments;
    this.nestedComments = this.nest();
  }

  getComments() {
    return this.comments;
  }

  getNestedComments() {
    return this.nestedComments;
  }

  nest() {

    const comments = this.comments.slice();

    (function appendChildren(parent_id = null) {

      const childIndices = comments.map(comment => comment.parent_id).indicesOf(parent_id);

      childIndices.forEach(index => {
        const child = comments[index];

        if (parent_id) {
          const parentIndex = comments.findIndex(comment => comment.id === parent_id);
          if (!comments[parentIndex].children) {
             comments[parentIndex].children = [];
          }
          comments[parentIndex].children.push(child);
        }

        appendChildren(child.id);
      });

    })();

    return comments.filter(comment => comment.parent_id === null);
  }

}

const comments = [{
  id: 1,
  text: "Top level",
  parent_id: null
}, {
  id: 2,
  text: "Top level",
  parent_id: null
}, {
  id: 3,
  text: "Reply level 1",
  parent_id: 1
}, {
  id: 4,
  text: "Reply level 1",
  parent_id: 2
}, {
  id: 5,
  text: "Reply level 2",
  parent_id: 3
}];

getComments() 显示原始的 comments 数组已发生突变(它具有 children),但我希望它保持原始状态。我正在使用.slice() 创建一个副本,但由于某种原因它仍然会发生变异。任何想法为什么?

在这里编写代码:http://codepen.io/anon/pen/QpMWNJ?editors=1010

【问题讨论】:

  • .slice() 只会制作数组的浅拷贝。它不会复制其中的对象。
  • @4castle - 用什么代替?
  • 对于其他人:来自重复链接:const comments = this.comments.map(a => Object.assign({}, a))

标签: javascript


【解决方案1】:

使用对象映射,

const comments = this.comments.slice()
const cloneComments = comments.map(f => {
        let o = {}
        for(var i in f) o[i] = f[i]
        return o
    })

【讨论】:

    【解决方案2】:

    你的答案应该在这里 - What is the most efficient way to deep clone an object in JavaScript?

    如果您想避免使用 jQuery,请使用 JSON.parse(JSON.stringify(obj)) 解决方案 const comments = JSON.parse(JSON.stringify(this.comments));

    注意:如果存在循环依赖,这将中断

    如果您可以使用 jQuery,请使用extend 使用更简洁的方法

    // Deep copy
    var newObject = jQuery.extend(true, {}, oldObject);
    

    【讨论】:

    • 请将问题标记为重复,而不是重新发布相同的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2021-01-15
    • 2014-06-09
    相关资源
    最近更新 更多