Angular/Javascript:按值复制一个简单的数字而不引用

Angular/Javascript : Copy a simple number by value without reference

本文关键字:简单 一个 数字 引用 Javascript 复制 Angular      更新时间:2023-09-26

>我正在尝试复制一个包含id的简单范围变量而不引用它。

这是一段代码,显示了我在做什么:

.controller('ctl', function($scope, $rootScope, Resource) {
    var controllerScope = this;
    this.tId = 1;
    /* ... */
    this.addProject = function() {
      this.supportedProjects.push(this.add.project);
      this.supportedProjects = this.supportedProjects.map(function(object) {
        var id = angular.copy(controllerScope.tId);
        if (object.title.title)
          return {
            id: id,
            title: object.title.title,
          };
        else
          return {
            id: id,
            title: object.title,
          };
      });
      this.tId++;
    /* ... */
    };
}

在这种情况下,supportedProjects中的对象都包含相同的 id。那么没有参考的复制的正确方法是什么?

我不知道发生了什么。

编辑:是我在map功能上做错了。

不确定我是否理解您要做什么,但这应该有效:

this.supportedProjects = this.supportedProjects.map(function(object) {
    if (object.title.title)
      object.title = object.title.title;
    return object;
 });

试试这个:

.controller('ctl', function($scope, $rootScope, Resource) {
    var controllerScope = this;
    this.tId = 0;
    /* ... */
    this.addProject = function() {
      this.supportedProjects.push(this.add.project);
      this.supportedProjects = this.supportedProjects.map(function(object) {
        var id = controllerScope.tId + 1;
        if (object.title.title)
          return {
            id: id,
            title: object.title.title,
          };
        else
          return {
            id: id,
            title: object.title,
          };
      });
      controllerScope.tId++;
    /* ... */
    };
}