[英]Can I use the logical OR operator with Strings in function arguments in JS? Function does not evaluate the second string (I think)
I check the backend through Vuex to conditionally render error messages.我通过 Vuex 检查后端以有条件地呈现错误消息。 I have the following function:
我有以下 function:
const getByTitle = (memberTitle) => {
return state.errors.find(e => e.meta.memberTitle === memberTitle)
?.content.error.title;
}
Now, as an argument I would like to pass 2 strings, as there are 2 options in this component.现在,作为参数,我想传递 2 个字符串,因为此组件中有 2 个选项。
getNumber() {
return this.getErrorByMemberId('B2Bvr' || 'Cvr' || undefined);
},
If the correct value in the backend is Cvr , then in this case I unfortunately don't get the error message (because it comes after B2Bvr ).如果后端的正确值是Cvr ,那么在这种情况下我很遗憾没有收到错误消息(因为它出现在B2Bvr之后)。 If I change the order of the arguments (see following snippet) abd put the correct value first ( Cvr ), then it works and correctly displays the error message.
如果我更改 arguments 的顺序(请参阅以下代码段)abd 将正确的值放在第一位 ( Cvr ),然后它会工作并正确显示错误消息。
getNumber() {
return this.getErrorByMemberId('Cvr' || 'B2Bvr' || undefined);
},
Why does it stop in the first argument?为什么它在第一个参数中停止? And does not evaluate the second one?
并且不评估第二个? Which is the correct way to use Logical OR operators in parameters?
在参数中使用逻辑或运算符的正确方法是什么?
It stops at the first argument because that's the first argument that is truthy, so the other arguments are ignored.它在第一个参数处停止,因为这是第一个真实的参数,因此其他 arguments 将被忽略。 If you attempted to call the function with
undefined
first (falsy value), it would skip that one and send the second argument.如果您尝试首先调用
undefined
的 function(虚假值),它将跳过那个并发送第二个参数。
One way to accomplish your intended goal would be to send all possible arguments as an array of arguments and use Array.includes() in your function:实现预期目标的一种方法是将所有可能的 arguments 作为 arguments 的数组发送,并在 function 中使用Array.includes() :
getNumber() {
return this.getErrorByMemberId(['Cvr', 'B2Bvr', undefined]);
},
const getByTitle = (memberTitleArray) => {
return state.errors.find(e => memberTitleArray.includes(e.meta.memberTitle))
?.content.error.title;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.