Javascript 不想在循环中更改对象值

标签 javascript angularjs

我需要将对象发送到 api。但我需要在循环的每一步中更改对象的一个​​值。

this.task = {
    RowId: 0
};

var taskWithFid = [];
var fids = [1,2,3,4,5];
var taskTemp = this.task;

fids.map(function(fid){                    
    taskTemp.RowId = fid;
    taskWithFid.push(taskTemp);
}.bind(this));

我希望 taskWithFid 数组像这样:

[
    { RowId: 1 },
    { RowId: 2 },
    { RowId: 3 },
    { RowId: 4 },
    { RowId: 5 }
]

但我明白了:

[
    { RowId: 5 },
    { RowId: 5 },
    { RowId: 5 },
    { RowId: 5 },
    { RowId: 5 }
]

你能帮我吗?

Here is the code:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <link rel="stylesheet" href="style.css">
        <script data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js" data-require="angular.js@1.2.x"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl as item">

    <h1>Hello Plunker!</h1
    <div>{{item.taskWithFid}}</div>  
  </body>

</html>

最佳答案

问题在于您将同一个对象插入数组中,并且在这样做时您正在更改它的 RowId。所以最后,当你把它改为5时,全部都是5。你需要创建单独的对象:

fids.map (function(fid) {                    
  taskWithFid.push({RowId: fid});
}.bind(this));

关于Javascript 不想在循环中更改对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32347301/

相关文章:

javascript - 如何在 AngularJS 中遍历模型数据?

javascript - 如何检测指令中的用户交互

javascript - 使用内容脚本从 get 函数返回值

Javascript 制作测验单选按钮

angularjs - 获取 $injector :modulerr after including ['ngRoute' ]

angularjs - ng-Animate:如何为同级 div 设置动画?

javascript - ngRepeat with ngAnimate 在我的元素上设置 "data-ng-animate= 2"

javascript - 使用纯 JavaScript 将 JSON 文件转换为可排序表

javascript - Angular : Is it possible to make Angular directives, 例如 NgIf 和 NgFor,仅在我想要的时候检查它们绑定(bind)的变量?

javascript - 是否有另一种模拟对象拟合的方法 :fill on a video element so that all major browsers recognize it?