首页 > 其他分享 >JS 多个 if 判断丝滑

JS 多个 if 判断丝滑

时间:2022-08-30 08:58:02浏览次数:98  
标签:temparr 判断 console log 多个 JS fruit 丝滑 apple

  • 多个if判断,看着很乱,使用优雅的代码实现

一个判断

 if (fruit == 'apple' ) {
    console.log('red');
  }

俩个判断

 if (fruit == 'apple' || fruit == 'strawberry') {
    console.log('red');
  }

多个判断

 if (fruit == 'apple' || fruit == 'strawberry'|| fruit == 'cherry'|| fruit == 'cranberries') {
    console.log('red');
  }

多判断优雅代码

  • 第一种,使用map函数
// 多条件判断开始,如下
const arr = [
  'apple',
  'strawberry',
  'cherry',
  'cranberries'
]

const temparr = arr.map(item => item === 'apple')
console.log(temparr, 'temparr') // [true, false, false, false]
if (temparr.includes(true)) {
  // 条件符合,提示
    console.log(1)
} else {
  // 条件不符,提示
    console.log(2)
}
  • 第二种,使用 some 函数方法
// 多条件判断开始,如下
const arr = [
  0,
  'apple',
  'strawberry',
  'cherry',
  'cranberries'
]

const tempFlag = arr.some(item => item === 0)
console.log(tempFlag, 'tempFlag') // 0
if (tempFlag) {
  // 条件符合,提示
  console.log(1)
} else {
  // 条件不符,提示
  console.log(2)
}

一个细节,这里如果使用 find 函数,结果是 0 的话,判断为假

标签:temparr,判断,console,log,多个,JS,fruit,丝滑,apple
From: https://www.cnblogs.com/DL-CODER/p/16638073.html

相关文章

  • js 实现二叉树中序遍历
    varinorderTraversal=function(root){//迭代if(!root){return[];}letres=[];letstack=[];while(stack.length>......
  • js Linked List Generator All In One
    jsLinkedListGeneratorAllInOnejs链表生成器classListNode{constructor(val,next){this.val=(val===undefined?0:val)this.next=(nex......
  • js 实现解析和构造Url参数
    //解析获取的url中的参数为对象functionparseQueryString(url){if(!url){return{};}constqsArr=decodeURIComponent(url).split("?"......
  • 数据传输格式XML和JSON
    XML:可扩展标记语言格式臃肿,解析麻烦,需要用到第三库 JSON:JavaScript对象表示法都是字符串,解析简单 JSON可支持的数据类型只有六种数值、字符串、布尔值、null、对......
  • .NET 开源工作流: Slickflow流程引擎高级开发(十) -- BpmnJS流程设计器集成
    前言:在Slickflow产品开发过程中,前端流程设计器经历了几个不同的版本(jsPlumb,mxGraph等),目的是为了在设计流程时的用户体验更加良好,得到客户的好评和认可。BpmnJS流程设......
  • Node.js安装简介
    一、Node.js简介Node.js是一个开源和跨平台的JavaScript运行时环境。它几乎是任何类型项目的流行工具!Node.js在浏览器之外运行V8JavaScript引擎(GoogleChrome的内核)。这使......
  • JSP的文件上传和下载
    文件的上传和下载文件的上传和下载,是非常常见的功能。很多的系统中,或者软件中都经常使用文件的上传和下载。比如:微信头像,就使用了上传。邮箱中也有附件的上传和下载功能......
  • 21JSONP及Axios
    JSONP及Axiosjsonp概述:JSONP是一种跨域解决方案,它主要是利用了script标签不受跨域影响的特性来完成对应的请求操作。实际上是一个get请求。什么叫跨域同源策略(属于浏览......
  • 在NodeJS中安装babel
    安装babel安装babel打开终端,输入命令:npminstall--save-dev@babel/core@babel/cli@babel/preset-env@babel/node安装完毕之后,再次输入命令安装:npminstall--save@......
  • JS/TS算法---dp和贪心
    一、动态规划动态规划(dynamicprogramming,DP)是一种将复杂问题分解成更小的子问题来解决的优化技术。注意,动态规划和分而治之是不同的方法。分而治之方法是把问题分解......