首頁 > web前端 > js教程 > 主體

提升javascript開發速度與效率的20個小技巧

青灯夜游
發布: 2021-06-28 10:00:29
轉載
2476 人瀏覽過

提高javascript開發速度和效率在平時開發中位於一個很重要的地方,這篇文章給大家介紹一些日常任務中使用起來方便且實用的方法和小技巧,減少程式碼行數,提高工作效率,增加摸魚時間。

提升javascript開發速度與效率的20個小技巧

在我們的日常任務中,我們需要寫函數,如排序、搜尋、尋找惟一值、傳遞參數、交換值等,所以在這裡分享一下我工作多年珍藏的幾個常用技巧和方法,讓大家增加摸魚的時間。 【相關推薦:javascript學習教學

這些方法絕對會幫助你:

  • 減少程式碼行
  • Coding Competitions
  • 增加摸魚的時間

#1、宣告與初始化陣列

我們可以使用特定的大小來初始化數組,也可以透過指定值來初始化數組內容,大家可能用的是一組數組,其實二維數組也可以這樣做,如下:

const array = Array(5).fill(''); 
// 输出
(5) ["", "", "", "", ""]

const matrix = Array(5).fill(0).map(() => Array(5).fill(0))
// 输出
(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]
length: 5
登入後複製

2、求和,最小值和最大值

我們應該利用reduce 方法快速找到基本的數學運算。

const array  = [5,4,7,8,9,2];
登入後複製

求和

array.reduce((a,b) => a+b);
// 输出: 35
登入後複製

最大值

array.reduce((a,b) => a>b?a:b);
// 输出: 9
登入後複製

##最小值##

array.reduce((a,b) => a<b?a:b);
// 输出: 2
登入後複製

3、排序字串,數字或物件等陣列我們有內建的方法

sort()

reverse ()來排序字串,但是如果是數字或物件陣列呢

字串陣列排序

const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// 输出
(4) ["Joe", "Kapil", "Musk", "Steve"]

stringArr.reverse();
// 输出
(4) ["Steve", "Musk", "Kapil", "Joe"]
登入後複製

數字數組排序

const array  = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// 输出
(6) [1, 5, 10, 25, 40, 100]

array.sort((a,b) => b-a);
// 输出
(6) [100, 40, 25, 10, 5, 1]
登入後複製

物件陣列排序

const objectArr = [ 
    { first_name: &#39;Lazslo&#39;, last_name: &#39;Jamf&#39;     },
    { first_name: &#39;Pig&#39;,    last_name: &#39;Bodine&#39;   },
    { first_name: &#39;Pirate&#39;, last_name: &#39;Prentice&#39; }
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// 输出 
(3) [{…}, {…}, {…}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3
登入後複製

#4、從陣列中篩選到虛值

0

, undefined, null, false, "", ''這樣的假值可以透過下面的技巧輕易地過濾掉。 <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">const array = [3, 0, 6, 7, &amp;#39;&amp;#39;, false]; array.filter(Boolean); // 输出 (3) [3, 6, 7]</pre><div class="contentsignin">登入後複製</div></div>

5、使用邏輯運算子處理需要條件判斷的情況

function doSomething(arg1){ 
    arg1 = arg1 || 10; 
// 如果arg1没有值,则取默认值 10
}

let foo = 10;  
foo === 10 && doSomething(); 
// 如果 foo 等于 10,刚执行 doSomething();
// 输出: 10

foo === 5 || doSomething();
// is the same thing as if (foo != 5) then doSomething();
// Output: 10
登入後複製

6、移除重複值

const array  = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// Output: [5, 4, 7, 8, 9, 2]
登入後複製

7、建立一個計數器物件或Map在大多數情況下,可以透過建立一個物件或Map來計數某些特殊字出現的頻率。

let string = &#39;kapilalipak&#39;;

const table={}; 
for(let char of string) {
  table[char]=table[char]+1 || 1;
}
// 输出
{k: 2, a: 3, p: 2, i: 2, l: 2}
登入後複製

const countMap = new Map();
  for (let i = 0; i < string.length; i++) {
    if (countMap.has(string[i])) {
      countMap.set(string[i], countMap.get(string[i]) + 1);
    } else {
      countMap.set(string[i], 1);
    }
  }
// 输出
Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}
登入後複製

8、三元運算子很酷

function Fever(temp) {
    return temp > 97 ? &#39;Visit Doctor!&#39;
      : temp < 97 ? &#39;Go Out and Play!!&#39;
      : temp === 97 ? &#39;Take Some Rest!&#39;: &#39;Go Out and Play!&#39;;;
}

// 输出
Fever(97): "Take Some Rest!" 
Fever(100): "Visit Doctor!"
登入後複製

9、循環方法的比較

    for
  • for..in 預設取得索引,但你可以使用arr[ index]
  • for..in
  • 也接受非數字,所以要避免使用。
  • forEach
  • , for...of 直接得到元素。 forEach 也可以得到索引,但
  • for...of
  • 不行。

10、合併兩個物件

const user = { 
 name: &#39;Kapil Raghuwanshi&#39;, 
 gender: &#39;Male&#39; 
 };
const college = { 
 primary: &#39;Mani Primary School&#39;, 
 secondary: &#39;Lass Secondary School&#39; 
 };
const skills = { 
 programming: &#39;Extreme&#39;, 
 swimming: &#39;Average&#39;, 
 sleeping: &#39;Pro&#39; 
 };

const summary = {...user, ...college, ...skills};

// 合并多个对象
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary School"
programming: "Extreme"
secondary: "Lass Secondary School"
sleeping: "Pro"
swimming: "Average"
登入後複製

11、箭頭函數 箭頭函數表達式是傳統函數表達式的一種替代方式,但受到限制,不能在所有情況下使用。因為它們有詞法作用域(父作用域),也沒有自己的

this

argument,因此它們引用定義它們的環境。 <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">const person = { name: &amp;#39;Kapil&amp;#39;, sayName() { return this.name; } } person.sayName(); // 输出 &quot;Kapil&quot;</pre><div class="contentsignin">登入後複製</div></div>但是這樣:

const person = {
name: &#39;Kapil&#39;,
sayName : () => {
    return this.name;
    }
}
person.sayName();
// Output
"
登入後複製

12、可選的鏈

const user = {
  employee: {
    name: "Kapil"
  }
};
user.employee?.name;
// Output: "Kapil"
user.employ?.name;
// Output: undefined
user.employ.name
// 输出: VM21616:1 Uncaught TypeError: Cannot read property &#39;name&#39; of undefined
登入後複製

13、洗牌一個陣列利用內建的

Math.random()

方法。 <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">const list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; list.sort(() =&gt; { return Math.random() - 0.5; }); // 输出 (9) [2, 5, 1, 6, 9, 8, 4, 3, 7] // 输出 (9) [4, 1, 7, 5, 3, 8, 2, 9, 6]</pre><div class="contentsignin">登入後複製</div></div>

14、雙問號語法

const foo = null ?? &#39;my school&#39;;
// 输出: "my school"

const baz = 0 ?? 42;
// 输出: 0
登入後複製

15、剩餘和展開語法#

function myFun(a,  b, ...manyMoreArgs) {
   return arguments.length;
}
myFun("one", "two", "three", "four", "five", "six");

// 输出: 6
登入後複製

const parts = [&#39;shoulders&#39;, &#39;knees&#39;]; 
const lyrics = [&#39;head&#39;, ...parts, &#39;and&#39;, &#39;toes&#39;]; 

lyrics;
// 输出: 
(5) ["head", "shoulders", "knees", "and", "toes"]
登入後複製

16、預設參數

const search = (arr, low=0,high=arr.length-1) => {
    return high;
}
search([1,2,3,4,5]);

// 输出: 4
登入後複製

17、將十進位轉換為二進位或十六進位

const num = 10;

num.toString(2);
// 输出: "1010"
num.toString(16);
// 输出: "a"
num.toString(8);
// 输出: "12"
登入後複製

18、使用解構來交換兩個數字

let a = 5;
let b = 8;
[a,b] = [b,a]

[a,b]
// 输出
(2) [8, 5]
登入後複製

19、單行的回文數檢查

function checkPalindrome(str) {
  return str == str.split(&#39;&#39;).reverse().join(&#39;&#39;);
}
checkPalindrome(&#39;naman&#39;);
// 输出: true
登入後複製

#20、將Object屬性轉換為屬性陣列

const obj = { a: 1, b: 2, c: 3 };

Object.entries(obj);
// Output
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3

Object.keys(obj);
(3) ["a", "b", "c"]

Object.values(obj);
(3) [1, 2, 3]
登入後複製
更多程式相關知識,請造訪:程式設計入門

! !

以上是提升javascript開發速度與效率的20個小技巧的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:segmentfault.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!