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]]

  

 

posted @ 2019-09-19 17:56  一根小雪糕  阅读(718)  评论(0编辑  收藏  举报