这看起来非常简单,但我似乎无法更新数组中 WorkSetTemplate 对象中 pos 字段的值。
代码如下:
export class WorkSetTemplate {
static alignPositionWithDisplay(coll: WorkSetTemplate[]): WorkSetTemplate[] {
for (let i = 0; i < coll.length; i++) {
coll[i].pos = i + 1;
}
return coll;
}
constructor(
public id?: number,
public nk?: string,
public pos?: number,
public name?: string,
public maintainerId?: number,
public airworthinessDirectiveIssueNumber?: string,
public workItemTemplates?: WorkItemTemplate[]
) {}
}
假设我从集合开始:
我用以下方式调用静态方法:
sets = WorkSetTemplate.alignPositionWithDisplay(sets);
我希望看到相同的对象排列,但 pos 值按顺序读取为 1, 2, 3(而不是 2, 1, 3)
但实际上并没有发生任何变化(即,它们仍然是 2, 1, 3,即使我在 for 循环中 console.log ,变化实际上发生了(在循环中)。所以当你退出循环。我显然在这里遗漏了一些非常基本的东西。有人可以告诉我我误解了什么吗?
最佳答案
这里的场景缺少一些东西,因为项目可能会发生变化(有或没有返回值分配)。
interface WorkItemTemplate {
name: string;
}
class WorkSetTemplate {
static alignPositionWithDisplay(coll: WorkSetTemplate[]): WorkSetTemplate[] {
for (let i = 0; i < coll.length; i++) {
coll[i].pos = i + 1;
}
return coll;
}
constructor(
public id?: number,
public nk?: string,
public pos?: number,
public name?: string,
public maintainerId?: number,
public airworthinessDirectiveIssueNumber?: string,
public workItemTemplates?: WorkItemTemplate[]
) {}
}
let items = [
new WorkSetTemplate(5, 'ABC3', 1),
new WorkSetTemplate(5, 'XYZ1', 1),
new WorkSetTemplate(5, 'ABC1', 1),
];
console.log(JSON.stringify(items));
// [
// { "id": 5, "nk": "ABC3", "pos": 1 },
// { "id": 5, "nk": "XYZ1", "pos": 1 },
// { "id": 5, "nk": "ABC1", "pos": 1 }
// ]
// Side note - the objects are changed regardless of assignment
WorkSetTemplate.alignPositionWithDisplay(items);
console.log(JSON.stringify(items));
// [
// { "id": 5, "nk": "ABC3", "pos": 1 },
// { "id": 5, "nk": "XYZ1", "pos": 2 },
// { "id": 5, "nk": "ABC1", "pos": 3 }
// ]
使用转译代码进行演示:
var WorkSetTemplate = /** @class */ (function () {
function WorkSetTemplate(id, nk, pos, name, maintainerId, airworthinessDirectiveIssueNumber, workItemTemplates) {
this.id = id;
this.nk = nk;
this.pos = pos;
this.name = name;
this.maintainerId = maintainerId;
this.airworthinessDirectiveIssueNumber = airworthinessDirectiveIssueNumber;
this.workItemTemplates = workItemTemplates;
}
WorkSetTemplate.alignPositionWithDisplay = function (coll) {
for (var i = 0; i < coll.length; i++) {
coll[i].pos = i + 1;
}
return coll;
};
return WorkSetTemplate;
}());
var items = [
new WorkSetTemplate(5, 'ABC3', 1),
new WorkSetTemplate(5, 'XYZ1', 1),
new WorkSetTemplate(5, 'ABC1', 1),
];
console.log(JSON.stringify(items));
WorkSetTemplate.alignPositionWithDisplay(items);
console.log(JSON.stringify(items));
关于javascript - 我似乎无法更新 javascript/typescript 中数组中对象字段的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53498525/