gpt4 book ai didi

javascript - 在javascript中返回没有变异的对象

转载 作者:行者123 更新时间:2023-11-29 16:01:53 25 4
gpt4 key购买 nike

下面的功能是否相同?我在 redux 表单中使用它,因为我的表单只有一个字段,我想我不需要循环,但第二个字段的行为不一样我想知道为什么

//working
export default values => {
let errors = {}
;['email'].forEach(field => {
if (!values.email) {
errors.email = `Email cannot be empty.`
}
})
return errors
}

对比

//is this the same as the above?
export default values => {
if (!values.email) {
return {
errors: {
email: `Email cannot be empty.`
}
}
}
}

最佳答案

这两个函数在功能上是等效的。

你的第一个函数总是返回一个对象:

export default values => {
let errors = {} // this errors object is always returned, regardless
// of the validity of fields
;['email'].forEach(field => {
if (!values.email) {
errors.email = `Email cannot be empty.`
}
})
return errors // Object always gets returned
}

然而,如果 values.email 是假的,你的第二个函数只返回一个对象:

export default values => {
if (!values.email) {
// Result only returned if !values.email
return {
errors: {
email: `Email cannot be empty.`
}
}
}
// If values.email is "truthy", then undefined is returned
}

总而言之,如果 values.email 为假,则第二个函数返回定义的结果;如果 values.email 为真,则返回未定义的结果,这与您的第一个函数不同,在所有情况下都会返回定义的结果。

您可以考虑对第二个函数进行以下更改,使其与第一个函数的行为方式类似:

export default values => {
if (!values.email) {
return {
errors: {
email: `Email cannot be empty.`
}
}
}
// If values.email is "truthy", then return empty error object
return {}
}

关于javascript - 在javascript中返回没有变异的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51923515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com