優化 JS 條件語句及JS 數組經常使用方法, ---- 看完絕對對往後開發有用

前言: 平常所說的優化優化、最後咱們到底優化了哪些,不如讓咱們從代碼質量開始;我的以爲簡潔簡化代碼其實以爲存在感挺強烈的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 > 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 redif (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.數組求和
[1,2,3,4].arr.reduce(function (prev, cur) {
return prev + cur;
},0) // 10
10.數組排序
[1,2,3,4].sort(); // [1, 2,3,4],默認是升序
[1,2,3,4].sort((a, b) => b - a); // [4,3,2,1] 降序
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.類數組轉化爲數組
Array.prototype.slice.call(arguments) //arguments是類數組(僞數組)
Array.prototype.slice.apply(arguments)
Array.from(arguments)
[...arguments]
13.對象和數組轉化
Object.keys({name:'張三',age:14}) //['name','age']
Object.values({name:'張三',age:14}) //['張三',14]
Object.entries({name:'張三',age:14}) //[[name,'張三'],[age,14]]
14.扁平化n維數組
[1,[2,3]].flat(2) //[1,2,3]
[1,[2,3,[4,5]].flat(3) //[1,2,3,4,5]
[1[2,3,[4,5[...]].flat(Infinity) //[1,2,3,4...n]

結語: 有不懂或有錯誤之處歡迎留言指正;但願看後對你們有用 app

文章部分參考: http://blog.jobbole.com/114671/函數

相關文章
相關標籤/搜索