js 条件方法、数组方法
经常写代码写的很多很累赘,看看下面例子,争取以后代码简洁简化。个人也觉得简洁分明的代码很重要。
本文来自另一篇博客:https://www.cnblogs.com/ljx20180807/p/10844892.html。
感觉内容很好用,方便以后快速学习。
1.获取URL中 ?后的携带参数
// 获取URL的查询参数
let params={}
location.search.replace(/([^?&=]+)=([^&]+)/g, (_,k,v) => parmas[k] = v);
console.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 > 10) {
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 red
if (quantity > 10) {
console.log('big quantity');
}
}
4.使用默认的函数参数和解构
// 优化前
function test(fruit,quantity ) {
const q = quantity || 1;
console.log ( );
if (fruit && fruit.name) {
console.log (fruit.name);
} else {
console.log('unknown');
}
}
// 优化后
function test({name} = {},quantity = 1) {
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([
[1, () => {
// ...
}],
[2, () => {
// ...
}],
[3, () => {
// ...
}]
])
actions.get(val).call(this)
6.数组 串联(每一项是否都满足)使用 Array.every ; 并联(有一项满足)Array.some 过滤数组 每项设值
// 每一项是否满足
[1,2,3].every(item=>{return item > 2}) // false
// 有一项满足
[1,2,3].some(item=>{return item > 2}) // true
// 过滤数组
[1,2,3].filter(item=>{return item > 2}) // [3]
// 每项设值
[1,2,3].fill(false) // [false,false,false]
7.数组去重
Array.from(new Set(arr))
[...new Set(arr)]
8.数组合并
[1,2,3,4].concat([5,6]) // [1,2,3,4,5,6]
[...[1,2,3,4],...[4,5]] // [1,2,3,4,5,6]
[1,2,3,4].push.apply([1,2,3,4],[5,6]) // [1,2,3,4,5,6]
9.数组求和
const all = [
{
name: 'Tom',
age: 10
},
{
name: 'Jack',
age: 11
},
{
name: 'Jun',
age: 11
}
]
// total 总和
console.log(all.reduce(function (total, cur) {
return total + cur.age;
}, 0))
10.数组排序
const arr = [43, 1, 65, 3, 2, 7, 88, 212, 191]
// 升序 第一位数字从小到大
console.log(arr.sort())
// 升序 从小到大
console.log(arr.sort((x, y) => {
return x - y
}))
// 降序
console.log(arr.sort((x, y) => {
return y - x
})) // 按照 age升序/降序
const obj = [
{
name: 'tom',
age: 1
},
{
name: 'tom4',
age: 81
},
{
name: 'tom3',
age: 31
},
{
name: 'tom2',
age: 2
}
]
console.log(obj.sort((x, y) => {
return y.age - x.age
}))
11.数组 判断是否包含值
[1,2,3].includes(4) //false
[1,2,3].indexOf(4) //-1 如果存在换回索引
[1, 2, 3].find((item)=>item===3)) //3 如果数组中无值返回undefined
[1, 2, 3].findIndex((item)=>item===3)) //2 如果数组中无值返回-1
12.对象和数组转化
Object.keys({name:'张三',age:14}) //['name','age']
Object.values({name:'张三',age:14}) //['张三',14]
Object.entries({name:'张三',age:14}) //[[name,'张三'],[age,14]]
js 条件方法、数组方法的更多相关文章
- js中的数组方法
数组的方法有数组原型方法,也有从object对象继承来的方法,这里我们只介绍数组的原型方法,数组原型方法主要有以下这些: join()push()和pop()shift() 和 unshift()so ...
- js中常用数组方法concat join push pop slice splice shift
javascript给我们很多常用的 数组方法,极大方便了我们做程序.下面我们来介绍下常用的集中数组方法. 比如 concat() join() push() pop() unshift() shif ...
- js学习笔记——数组方法
join() 把数组中所有元素转化为字符串并连接起来,并返回该字符串, var arr=[1,2,3]; var str=arr.join("#"); //str="1# ...
- 【笔记】JS中的数组方法
push()方法:可以向数组的末尾添加一个或者多个元素,并且返回新的长度 pop()方法:可以删除数组最后一个元素,并且返回被删除的元素,注意:如果数组是空的,该方法不进行任何操作,返回undef ...
- js常用的数组方法
1.创建数组的基本方法: 1.1 空数组 var obj=new Array(); 1.2 指定长度数组 var obj=new Array(size); ...
- JS快速构建数组方法
一.常用(普通)数组的构建 1.1 直接构建 let arr = ['mock1', 'mock2', 'mock3'] 1.2 通过new Array let arr = newArray('moc ...
- js数组方法汇总
下面主要汇总一下数组的方法 数组方法: 1.检测是否为数组的方法:Array.isArrray(); var arr=[1,2,3,4,5]; var str='string'; console.lo ...
- 数组的indexOf方法--数组去重
数组的indexOf方法 数组方法大家再熟悉不过了,却忽略了数组有 indexOf 这个方法(我个人感觉). 干说不练瞎扯淡,遇到了什么问题,注意⚠️点又在哪里? let arr = ['orange ...
- 从js的repeat方法谈js字符串与数组的扩展方法
js将字符串重复N次的repeat方法的8个版本 /* *@desc: 将一个字符串重复自身N次 */ //版本1:利用空数组的join方法 function repeat(target, n) { ...
- 几个关于js数组方法reduce的经典片段
以下是个人在工作中收藏总结的一些关于javascript数组方法reduce的相关代码片段,后续遇到其他使用这个函数的场景,将会陆续添加,这里作为备忘. javascript数组那么多方法,为什么我要 ...
随机推荐
- leetcode-hard-array-41. First Missing Positive-NO
mycode class Solution(object): def firstMissingPositive(self, nums): """ :type nums: ...
- Movidius的深度学习入门
1.Ubuntu虚拟机上安装NC SDK cd /home/shine/Downloads/ mkdir NC_SDK git clone https://github.com/movidius/nc ...
- 自定义application的全局捕获异常实现
package com.loaderman.global; import android.app.Application; import android.os.Environment; import ...
- js图片轮播效果实现代码
首先给大家看一看js图片轮播效果,如下图 具体思路: 一.页面加载.获取整个容器.所有放数字索引的li及放图片列表的ul.定义放定时器的变量.存放当前索引的变量index 二.添加定时器,每隔2秒钟i ...
- 小D课堂 - 新版本微服务springcloud+Docker教程_2_01传统架构演进到分布式架构
笔记 第二章 架构演进和分布式系统基础知识 1.传统架构演进到分布式架构 简介:讲解单机应用和分布式应用架构演进基础知识 (画图) 高可用 LVS+keepalive :负载均衡的知识点 1. ...
- 使用shiro遇到的问题
Caused by: java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException 解决问题:缺少一个依赖的缓存jar 添加: <d ...
- js中的堆内存和栈内存
我们常常会听说什么栈内存.堆内存,那么他们到底有什么区别呢,在js中又是如何区分他们的呢,今天我们来看一下. 一.栈内存和堆内存的区分 一般来说,栈内存主要用于存储各种基本类型的变量,包括Boolea ...
- go使用go-redis操作redis 连接类型,pipline, 发布订阅
内容: 一 . 客户端Client(普通模式,主从模式,哨兵模式)二. conn连接(连接, pipline, 发布订阅等)三. 示例程序(连接, pipline, 发布订阅等)客户端Client 普 ...
- golang struct结构体初始化的几种方式
type User struct { Id int `json:"id" orm:"auto"` // 用户名 Username string `json:&q ...
- Spring MVC 源码 分析
spring web 源码 @HandlesTypes(WebApplicationInitializer.class) public class SpringServletContainerInit ...