有没有办法让下面的代码更简单?
let objectModified = this.objectsModified.filter(objectModified => {
if(objectModified.index === this.objectCurrent.index) {
return objectModified;
}
})[0]; /*[0] because there is no way the could be .length > 1 */
if(objectModified) {
let index = this.objectsModified.indexOf(objectModified);
this.objectsModified[index] = "something";
}
else {
this.objectsModified.push("something");
}
在我看来,必须有一个更智能,更易读的解决方案。但我无法理解。
答案 0 :(得分:2)
使用findIndex
会简化事情:
let objectModifiedIndex = this.objectsModified.findIndex(
objectModified => objectModified.index === this.objectCurrent.index
);
if (objectModifiedIndex !== -1) {
this.objectsModified[objectModifiedIndex] = "something";
} else {
this.objectsModified.push("something");
}