提高javascript開發速度和效率在平時開發中位於一個很重要的地方,這篇文章給大家介紹一些日常任務中使用起來方便且實用的方法和小技巧,減少程式碼行數,提高工作效率,增加摸魚時間。
在我們的日常任務中,我們需要寫函數,如排序、搜尋、尋找惟一值、傳遞參數、交換值等,所以在這裡分享一下我工作多年珍藏的幾個常用技巧和方法,讓大家增加摸魚的時間。 【相關推薦: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: 'Lazslo', last_name: 'Jamf' },
{ first_name: 'Pig', last_name: 'Bodine' },
{ first_name: 'Pirate', last_name: 'Prentice' }
];
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
, ""
, ''
這樣的假值可以透過下面的技巧輕易地過濾掉。 <pre class='brush:php;toolbar:false;'>const array = [3, 0, 6, 7, &#39;&#39;, false];
array.filter(Boolean);
// 输出
(3) [3, 6, 7]</pre>
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 = 'kapilalipak'; 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 ? 'Visit Doctor!'
: temp < 97 ? 'Go Out and Play!!'
: temp === 97 ? 'Take Some Rest!': 'Go Out and Play!';;
}
// 输出
Fever(97): "Take Some Rest!"
Fever(100): "Visit Doctor!"
9、循環方法的比較
- for
- 和
for..in
預設取得索引,但你可以使用arr[ index]
。 for..in - 也接受非數字,所以要避免使用。
- ,
for...of
直接得到元素。forEach 也可以得到索引,但
for...of - 不行。
10、合併兩個物件const user = {
name: 'Kapil Raghuwanshi',
gender: 'Male'
};
const college = {
primary: 'Mani Primary School',
secondary: 'Lass Secondary School'
};
const skills = {
programming: 'Extreme',
swimming: 'Average',
sleeping: 'Pro'
};
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
,因此它們引用定義它們的環境。 <pre class='brush:php;toolbar:false;'>const person = {
name: &#39;Kapil&#39;,
sayName() {
return this.name;
}
}
person.sayName();
// 输出
"Kapil"</pre>
但是這樣:
const person = { name: 'Kapil', 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 'name' of undefined
13、洗牌一個陣列利用內建的
Math.random()方法。 <pre class='brush:php;toolbar:false;'>const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
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>
14、雙問號語法const foo = null ?? 'my school';
// 输出: "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 = ['shoulders', 'knees']; const lyrics = ['head', ...parts, 'and', 'toes']; 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('').reverse().join('');
}
checkPalindrome('naman');
// 输出: 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中文網其他相關文章!

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Dreamweaver Mac版
視覺化網頁開發工具

SublimeText3 Linux新版
SublimeText3 Linux最新版