javascript - 为什么点表示法返回具有附加属性的对象,而扩展运算符不返回?
问题描述
我有一个函数可以根据条件返回一个新对象。为什么当我使用点表示法时它返回新对象而扩展运算符不返回
此行返回具有新属性的新对象
const newValue = values => {
const condition = "SUCCESS"
const result = values.filter(r => {
if(condition === "SUCCESS"){
r.codes = "Success Test"
return r
}
r.codes = "Fail Test"
return r
})
return result
}
此行返回没有新属性的旧对象
const newValue = values => {
const condition = "SUCCESS"
const result = values.filter(r => {
if(condition === "SUCCESS"){
return { ...r, codes: "Success Test" }
}
return { ...r, codes: "Fail Test" }
})
return result
}
预期结果应该是:
result = [{ name:"Hey", codes:"Success Test" }]
解决方案
filter
只关心您传递给它的函数是否返回一个值(可以强制转换为)是true
or false
。
在这两种情况下,您都返回一个对象。对象始终是真值,因此原始数组中的值保留在过滤后的数组中。
在您的第一个示例中,您返回的对象是您修改的原始对象。
In your second example, the object you return is a new object, so the original object is unmodified. Since filter
only cases about true
or false
, it always returns the original object (which will only have a new property on it if you modify the original).
You always return a true value, and never return a false value, which makes using filter
pointless.
It looks like you are trying to map
the array, not filter
it.
推荐阅读
- amazon-web-services - 使用 lambda_async 从 Aurora RDS 触发器访问 AWS Lambda?
- typescript - 如何创建一个接口是另一个接口的特化?
- typescript - 具有历史功能的类型脚本随机化器
- c++ - 为什么我的窗口函数没有消除谐波?
- javascript - 带有 ReactJS 的 Highcharts 3D 圆柱体
- c++ - 带有 getter/setter 的 memset 和 struct
- node.js - Docker 和 Webpack 热重载不起作用
- java - 如何确定双精度数的小数位数?
- typescript - 打字稿:检查类型不是任何
- c# - 实现镜头放大以放大 Windows 任务栏