我需要将对象发送到 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 }
]
你能帮我吗?
<!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/