Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用过滤器和其他工具更新JS/TS中的模型_Javascript_Typescript_Ecmascript 6 - Fatal编程技术网

Javascript 使用过滤器和其他工具更新JS/TS中的模型

Javascript 使用过滤器和其他工具更新JS/TS中的模型,javascript,typescript,ecmascript-6,Javascript,Typescript,Ecmascript 6,我有一个这样的模型: private model:Array<IMyTest> = []; 我在另一个组件中有一些代码,我想让isCorrect在true或false之间切换 所以我写了一个这样的方法,从这个开始: this.model.filter(q => q.testId === testId) ... 但我想让这个。一个返回集的模型如果为null则正确为true,如果为true则为false,如果为true则为false 如何正确地将其链接?我已经有一段时间没有做前

我有一个这样的模型:

private model:Array<IMyTest> = [];
我在另一个组件中有一些代码,我想让isCorrect在true或false之间切换

所以我写了一个这样的方法,从这个开始:

this.model.filter(q => q.testId === testId) ...
但我想让这个。一个返回集的模型如果为null则正确为true,如果为true则为false,如果为true则为false

如何正确地将其链接?我已经有一段时间没有做前端工作了

/////编辑以下答案时出错:

private updateTest(testId:number): void {

    this.model = this.model.forEach(q => q.testId === testId && q.isCorrect = !q.isCorrect);
}

我得到的错误是第一个this.model类型为void,不能分配给MyTest[]类型和=!q、 isCorrect在等号下有一条红线。

如果要使用
testId
切换更新项目的
isCorrect
,下面是您将要使用的内容

this.model=this.model.map(
q=>q.testId==testId?{…q,isCorrent:!q.isCorrent}:q
)
如果您不想拥有一个新对象(
this.model
),那么它应该是

this.model.forEach(
q=>q.testId==testId&&(q.isCorrect=!q.isCorrect)
)


过滤器将返回一个带有
testId
项的新对象,在此之后,您必须将其插入
this.model
数组中,如果您想将其链接起来,它将不会像这样。

在=!q、 是否更正,因为在我的代码中找不到q?我正在使用forEach@cdub用
这个数组检查一下。模型
数组,可能有空对象。是的,有问题。我的编辑在上面的代码中。the=!他说:“我还是。不确定why@cdub更新并测试后,应包装
(q.isCorrent=!q.isCorrent)
。很抱歉出错。此.model.filter(q=>q.testId==testId).forEach(q=>q.isCorrect=!q.isCorrect)---这有用吗?
private updateTest(testId:number): void {

    this.model = this.model.forEach(q => q.testId === testId && q.isCorrect = !q.isCorrect);
}