首页 > 其他分享 >对`a == ('1'||'2'||'3') ? false : true`写法进行改进,写出你优化后的方法

对`a == ('1'||'2'||'3') ? false : true`写法进行改进,写出你优化后的方法

时间:2024-12-05 09:22:43浏览次数:11  
标签:validValues false true values result const 写法

The original expression a == ('1'||'2'||'3') ? false : true is flawed and doesn't work as intended. The ('1'||'2'||'3') part will always evaluate to '1' because of how the || (OR) operator works with strings. It short-circuits and returns the first truthy value. Therefore, the comparison is equivalent to a == '1' ? false : true. This only checks if a is strictly equal to the string '1'.

Here are several improved ways to achieve the intended logic (checking if a is one of '1', '2', or '3'), along with explanations and best practices:

1. Array includes() (Most recommended):

const validValues = ['1', '2', '3'];
const result = validValues.includes(a);

This is the cleanest and most readable solution. It creates an array of valid values and uses the includes() method to check if a is present in the array.

2. Set has() (Good for performance with many values):

const validValues = new Set(['1', '2', '3']);
const result = validValues.has(a);

If you have a large number of valid values, using a Set is more performant for lookups than an array. The has() method checks for the presence of a in the set.

3. Multiple OR conditions (Okay for a few values):

const result = a === '1' || a === '2' || a === '3';

This is straightforward for a small number of values. It explicitly checks if a is strictly equal to any of the valid strings.

4. Regular Expression (For more complex patterns):

const result = /^(1|2|3)$/.test(a);

This uses a regular expression to check if a matches one of the valid values. This is useful if you have more complex patterns to match, but for simple cases, the other methods are preferred for readability.

5. Switch statement (Less common for this scenario):

let result;
switch (a) {
  case '1':
  case '2':
  case '3':
    result = true;
    break;
  default:
    result = false;
}

While functional, a switch statement is less concise for this specific use case compared to the other options.

Important Considerations:

  • Strict Equality (===): Always use strict equality (===) in JavaScript comparisons, especially when dealing with strings and numbers, to avoid unexpected type coercion issues.
  • Type Safety: If a can be something other than a string (e.g., a number), you might need to convert it to a string before the comparison using a.toString() or String(a). For example: validValues.includes(String(a)).

Choose the method that best suits your needs and coding style. For simple cases with a few values, the array includes() method is generally the most recommended for its clarity and simplicity. For a larger number of values, consider a Set. If you have more complex patterns, regular expressions might be appropriate.

标签:validValues,false,true,values,result,const,写法
From: https://www.cnblogs.com/ai888/p/18587762

相关文章

  • 光标自动定位到起始位置 contenteditable="true" ,v-html绑定内容,div可编辑时,光标移到
    出现这个问题原因:(1)通过打断点可以看到,当你输入的时候触发input事件,提交值给父组件中的v-model;(2)但因为在子组件中又监听了v-model的值,所以整体形成了闭环;(3)还需要重点说明的是光标问题,contenteditable与v-html所在的元素值的改变如果不是通过输入而是通过赋值实现,光标就会跑到最......
  • Dede更新栏目时出现 DedeTag Engine Create File False 错误
    原因:要创建的目录或文件没有写入权限。解决办法:定位出错文件:修改 include/dedetag.class.php 文件,搜索 "DedeTagEngineCreateFileFalse",找到以下代码:  $fp=@fopen($filename,"w")ordie("DedeTagEngineCreateFileFalse");修改为:  $fp......
  • vue基础之4:el与data的两种写法、理解MVVM、Object.defineProperty方法、数据代理
    欢迎来到“雪碧聊技术”CSDN博客!在这里,您将踏入一个专注于Java开发技术的知识殿堂。无论您是Java编程的初学者,还是具有一定经验的开发者,相信我的博客都能为您提供宝贵的学习资源和实用技巧。作为您的技术向导,我将不断探索Java的深邃世界,分享最新的技术动态、实战经验以及项目......
  • [React]antd表单校验函数写法
    来自文心一言通过 rules 属性来定义校验规则,其中可以包含自定义的校验函数 validatorimportReactfrom'react';import{Form,Input,Button}from'antd';constMyForm=()=>{const[form]=Form.useForm();//自定义校验函数constcheckUsername=(......
  • 快速排序两种写法的注意点
    1.自创写法(根据快速排序原理,使用while)这里有一组hack数据就是数组中存在两个元素值相等的情况,此时backup[i]和backup[j]相等,此时交换之后如果不写i++,j++就会造成i,j指针在下一次循环中,仍然会卡在原来的位置,从而造成死循环。所以每两个元素交换完了之后一定要保证指......
  • Q:CRON表达式,Linux和Java的不同写法
    CRON表达式是一个字符串,包含五个到七个由空格分隔的字段(每种软件不一样),表示一组时间,通常作为执行某个程序的时间表。调度精度:Linux的cron调度精度为分钟级别,最小粒度为分钟,而Java中的Quartz框架可以支持秒级别的调用。灵活性:Quartz框架提供了丰富的调度功能,可以支持一些复......
  • 列举出你最常用的meta标签的写法和作用
    以下列举一些前端开发中最常用的meta标签,以及它们的写法和作用:字符集:<metacharset="UTF-8">声明文档的字符编码为UTF-8,这几乎是所有网页都应该使用的。它确保文本能够正确显示,避免乱码。视口设置(Viewport):<metaname="viewport"content="width=device-width,in......
  • 解释下为什么`{} + [] === 0`为true?
    在JavaScript中,{}+[]===0的结果为true,这是由于JavaScript隐式类型转换和运算符优先级的复杂交互造成的。让我们逐步分解:{}的歧义:{}在JavaScript中既可以表示一个空代码块,也可以表示一个空对象字面量。在这个表达式中,由于加号运算符的存在,JavaScript引擎将......
  • C语言-冒泡排序和选择排序的多种写法
     ......
  • AI绘画经验技巧干货,Stable Diffusion提示词Prompt的通用写法
    在使用StableDiffusionwebUI创作的时候,提示词Prompt并不是越多越好,也不可以随意堆积,可以按照下面的这个通用公式来写提示词描述,AI模型读取Promot是有先后顺序的,会按从前向后顺序解读。前缀+主体+场景+后缀更多stablediffusion模型插件以及安装包可以扫......