首页 > 解决方案 > 为什么点表示法返回具有附加属性的对象,而扩展运算符不返回?

问题描述

我有一个函数可以根据条件返回一个新对象。为什么当我使用点表示法时它返回新对象而扩展运算符不返回

此行返回具有新属性的新对象


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" }]

标签: javascript

解决方案


filter只关心您传递给它的函数是否返回一个值(可以强制转换为)是trueor 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.


推荐阅读