前言: 日常所说的优化优化、最后我们到底优化了哪些,不如让我们从代码质量开始;个人觉得简洁简化代码其实觉得存在感挺强烈的QAQ

1. 获取URL中 ?后的携带参数; 这是我见过最简洁的了,若有更简洁的请及时留言并附上代码怼我
// 获取URL的查询参数
let params={}
location.search.replace(/([^?&=]+)=([^&]+)/g, (_,k,v) => parmas[k] = v);
cosnole.log(params) // ?a=b&c=d&e=f => {a: "b", c: "d", e: "f"}
2. 对多个条件筛选用 Array.includes
// 优化前
function test(fruit) {
if (fruit == 'apple' || fruit == 'strawberry') {
console.log('red');
}
}
// 优化后
function test(fruit) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (redFruits.includes(fruit)) {
console.log('red');
}
}
3. 更少的嵌套,尽早返回
// 优化前
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (!fruit) throw new Error('No fruit!');
if (redFruits.includes(fruit)) {
  if (quantity > ) {
console.log('big quantity');
}
}
}
// 优化后
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (!fruit) throw new Error('No fruit!'); // condition 1: throw error early
if (!redFruits.includes(fruit)) return; // condition 2: stop when fruit is not redif (quantity > ) {
console.log('big quantity');
}
}
4. 使用默认的函数参数和解构
//  优化前
function test(fruit,quantity ) {
const q = quantity || ;
console.log ( );
if (fruit && fruit.name) {
console.log (fruit.name);
} else {
console.log('unknown');
}
}
// 优化后
function test({name} = {},quantity = ) {
console.log (name || 'unknown');
console.log (quantity );
}
5. 选择 Map 或对象字面量,而不是 Switch 语句 或者 if else
// 优化前
function test(color) {
switch (color) {
case 'red':
return ['apple', 'strawberry'];
case 'yellow':
return ['banana', 'pineapple'];
case 'purple':
return ['grape', 'plum'];
default:
return [];
}
}
// 优化后 方式1
const fruitColor = {
red: ['apple', 'strawberry'],
yellow: ['banana', 'pineapple'],
purple: ['grape', 'plum']
};
function test(color) {
return fruitColor[color] || [];
}
// 优化后 方式2
const fruitColor = new Map()
.set('red', ['apple', 'strawberry'])
.set('yellow', ['banana', 'pineapple'])
.set('purple', ['grape', 'plum']); function test(color) {
return fruitColor.get(color) || [];
}
// if... if else... else... 优化方法
const actions = new Map([
[, () => {
// ...
}],
[, () => {
// ...
}],
[, () => {
// ...
}]
])
actions.get(val).call(this)
6.数组 串联(每一项是否都满足)使用 Array.every ; 并联(有一项满足Array.some   过滤数组   每项设值
// 每一项是否满足
[,,].every(item=>{return item > }) // false
// 有一项满足
[,,].some(item=>{return item > }) // true
// 过滤数组
[,,].filter(item=>{return item > }) // [3]
// 每项设值
[,,].fill(false) // [false,false,false]
7. 数组去重
Array.from(new Set(arr))
[...new Set(arr)]
8.数组合并
[,,,].concat([,])  // [1,2,3,4,5,6]
[...[,,,],...[,]] // [1,2,3,4,5,6]
[,,,].push.apply([,,,],[,]) // [1,2,3,4,5,6]
9.数组求和
[,,,].arr.reduce(function (prev, cur) {
return prev + cur;
},) //
10.数组排序
[,,,].sort(); // [1, 2,3,4],默认是升序
[,,,].sort((a, b) => b - a); // [4,3,2,1] 降序
11.数组 判断是否包含值
[,,].includes() //false
[,,].indexOf() //-1 如果存在换回索引
[, , ].find((item)=>item===)) //3 如果数组中无值返回undefined
[, , ].findIndex((item)=>item===)) //2 如果数组中无值返回-1
12.类数组转化为数组
Array.prototype.slice.call(arguments) //arguments是类数组(伪数组)
Array.prototype.slice.apply(arguments)
Array.from(arguments)
[...arguments]
13.对象和数组转化
Object.keys({name:'张三',age:}) //['name','age']
Object.values({name:'张三',age:}) //['张三',14]
Object.entries({name:'张三',age:}) //[[name,'张三'],[age,14]]
14.扁平化n维数组
[,[,]].flat() //[1,2,3]
[,[,,[,]].flat() //[1,2,3,4,5]
[[,,[,[...]].flat(Infinity) //[1,2,3,4...n]

结语: 有不懂或有错误之处欢迎留言指正;希望看后对大家有用

文章部分参考:http://blog.jobbole.com/114671/

优化 JS 条件语句及JS 数组常用方法, ---- 看完绝对对日后开发有用的更多相关文章

  1. 优化 JS 条件语句的 5 个技巧

    优化 JS 条件语句的 5 个技巧 原创: 前端大全 前端大全 昨天 (给前端大全加星标,提升前端技能) 编译:伯乐在线/Mr.Dcheng http://blog.jobbole.com/11467 ...

  2. JS条件语句优化

    1.对多个条件使用Array.includes eg: function test(fruit){                                                    ...

  3. js条件语句之职责链数组

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. js条件语句,用if...else if....else方程ax2+bx+c=0一元二次方程。求根

    if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码 if...else 语句 - 当条件为 true 时执行代码,当条件为 false 时执行其他代码 if...else if... ...

  5. JAVAscript学习笔记 js条件语句 第三节 (原创) 参考js使用表 (2017-09-14 15:55)

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. js条件语句初步练习

    var a=18            if(a<10){                alert("便宜")            }            else{  ...

  7. 廖雪峰js教程笔记6 generator一个坑 看完python在回来填坑

    generator(生成器)是ES6标准引入的新的数据类型.一个generator看上去像一个函数,但可以返回多次. ES6定义generator标准的哥们借鉴了Python的generator的概念 ...

  8. vue条件语句、循环语句、计算属性、侦听器监听属性

    因为 v-if 和v-for是一个指令,所以必须将它添加到一个元素上.但是如果想切换多个元素呢?此时可以把一个 <template> 元素当做不可见的包裹元素,并在上面使用 v-if.最终 ...

  9. JS 优化条件语句的5个技巧

    前言 在使用 JavaScript 的时候,有时我们会处理大量条件语句,这里有5个技巧帮助我们编写更简洁的条件语句. 一.对多个条件使用 Array.includes 例子: function con ...

随机推荐

  1. C#文件压缩:ICSharpCode.SharpZipLib生成zip、tar、tar.gz

    原文地址:https://blog.csdn.net/nihao198503/article/details/9204115 将代码原封不动的copy过来,只是因为有关tar的文章太少,大多都是zip ...

  2. Uploading multiple files asynchronously by blueimp jquery-fileupload

    Uploading multiple files asynchronously by blueimp jquery-fileupload   Solved. Fiddle: http://jsfidd ...

  3. jenkins入门-----(1)安装、配置

    Jenkins概念 Jenkins是一个开源的.可扩展的持续集成.交付.部署(软件/代码的编译.打包.部署)的基于web界面的平台.允许持续集成和持续交付项目,无论用的是什么平台,可以处理任何类型的构 ...

  4. python出现AttributeError: module ‘xxx’ has no attribute ‘xxx’错误时,两个解决办法

    运行python程序时,也许会出现这样的错误:AttributeError: module ‘xxx’ has no attribute ‘xxx’: 解决该错误有两种方法 1.手动安装该模块 2.检 ...

  5. React之js实现跳转路由

    1.新增知识 /* 实现js跳转路由:https://reacttraining.com/react-router/web/example/auth-workflow 1.要引入Redirect im ...

  6. 监控Linux服务器上python服务脚本

    提供给公司使用的测试平台这两天频繁地挂掉,影响到相关同事的正常使用,决定在服务器上写个监控脚本,监控到服务挂了就启动起来,一分钟检查一次.注:后台服务使用的是python.监控脚本如下: NUM=`p ...

  7. MySQL 创建函数报错 This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators

    问题描述 通过Navicat客户端,创建MySQL函数(根据的当前节点查询其左右叶子节点)时报错,报错信息如下: This function has none of DETERMINISTIC, NO ...

  8. SuperSocket 学习笔记-客户端

    客户端: 定义 private AsyncTcpSession client; 初始化 client = new AsyncTcpSession(); client.Connected += Clie ...

  9. 【SSM】---Spring+SpringMVC+Mybatis框架整合

    参考 百度经验 https://jingyan.baidu.com/article/2a1383288a85a9074a134f1b.html CSDN http://blog.csdn.net/ge ...

  10. MyBatis框架原理3:缓存

    上一篇[MyBatis框架原理2:SqlSession运行过程][1]介绍了MyBatis的工作流程,其中涉及到了MyBatis缓存的使用,首先回顾一下工作流程图: 如果开启了二级缓存,数据查询执行过 ...