從各方各面搜集整理的js編碼小技巧,吐血整理,強烈建議收藏
7個條件判斷簡化技巧
1. 多條件檢查
把多個值放在一個數組中,然后調用數組的 includes 方法。
//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}
2. 簡化 if true...else
對於不包含大邏輯的 if-else 條件,可以使用下面的快捷寫法。我們可以簡單地使用三元運算符來實現這種簡化。
// Longhand
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can use directly
let test = x > 10;
console.log(test);
如果有嵌套的條件,可以這么做。
let x = 300,
test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
3. if 判斷值是否存在
這是我們都在使用的一種常用的簡便技巧,在這里仍然值得再提一下。
// Longhand
if (test1 === true)
// or
if (test1 !== "")
// or
if (test1 !== null)
// Shorthand //it will check empty string,null and undefined too
if (test1)
注意:如果 test1 有值,將執行 if 之后的邏輯,這個操作符主要用於 null 或 undefinded 檢查。
4. 用於多個條件判斷的 && 操作符
如果只在變量為 true 時才調用函數,可以使用 && 操作符。
//Longhand
if (test1) {
callMethod();
}
//Shorthand
test1 && callMethod();
5. 比較后返回
我們也可以在 return 語句中使用比較,它可以將 5 行代碼減少到 1 行。
// Longhand
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe('test');
}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
console.log(val);
}
// Shorthand
function checkReturn() {
return test || callMe('test');
}
6. switch 簡化
我們可以將條件保存在鍵值對象中,並根據條件來調用它們。
// Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test
};
data[something] && data[something]();
7. 條件查找簡化
如果我們要基於不同的類型調用不同的方法,可以使用多個 else if 語句或 switch,但有沒有比這更好的簡化技巧呢?
// Longhand
if (type === 'test1') {
test1();
}
else if (type === 'test2') {
test2();
}
else if (type === 'test3') {
test3();
}
else if (type === 'test4') {
test4();
} else {
throw new Error('Invalid value ' + type);
}
// Shorthand
var types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value ' + type);
func();
空值檢查
使用操作符 ||
當我們創建了新變量,有時候想要檢查引用的變量是不是為非 null 或 undefined。JavaScript 確實有一個很好的快捷方式來實現這種檢查。
// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
let test2 = test1;
}
// Shorthand
let test2 = test1 || '';
使用操作符 ??
const test= null ?? 'default';
console.log(test);
// expected output: "default"
const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0
6個聲明變量、變量賦值技巧
1. 聲明變量
當我們想要聲明兩個具有相同的值或相同類型的變量時,可以使用這種簡寫。
//Longhand
let test1;
let test2 = 1;
//Shorthand
let test1, test2 = 1;
2. 給多個變量賦值
當我們想給多個不同的變量賦值時,這種技巧非常有用。
//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand
let [test1, test2, test3] = [1, 2, 3];
3. 簡便的賦值操作符
在編程過程中,我們要處理大量的算術運算符。這是 JavaScript 變量賦值操作符的有用技巧之一。
// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;
4. 對象屬性賦值
鍵值和鍵名一致時,可以省略 :鍵值
let test1 = 'a';
let test2 = 'b';
//Longhand
let obj = {test1: test1, test2: test2};
//Shorthand
let obj = {test1, test2};
5. 解構賦值
//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;
6. 在沒有第三個變量的情況下交換兩個變量
使用解構從數組中提取值。這可以應用於在沒有第三個的情況下交換兩個變量。
例如:
let x = 1;
let y = 2;
// LONGER FORMlet
temp = x;
x = y;
y = temp;
// SHORTHAND
[x, y] = [y, x];
7個JavaScript字符串方法
1. slice() 方法
slice() 方法是一個字符串方法,它允許我們復制和提取部分字符串。
結果,它以新字符串形式返回提取的部分。你也可以將此方法用於數組。
方法 slice() 接受兩個參數:
- 起始索引(要從其開始的字符索引)。
- 結束索引(要結束的字符的索引)。
下面是一個例子:
const str = "JavaScript is Awesome";
str.slice(0, 10); //returns "JavaScript"
在上面的例子中,我們使用了 slice 方法,並傳遞了兩個參數來將字符串的一部分從指定的索引提取到另一個。
如果需要,你也可以只傳遞一個參數。結果,它將從該索引參數中提取字符串,直到該字符串的最后一個索引。
下面是一個例子:
const str = "JavaScript is Awesome";
str.slice(14); //returns "Awesome"
str.slice(-7); //returns "Awesome"
如你所見,如果需要,你還可以傳遞負數,該方法將從字符串的末尾開始提取到開頭。
2. concat()方法
concat() 方法允許將字符串連接和組合在一起。這就像使用一元運算符 + 進行字符串連接。
下面是一個例子:
const tool = "JavaScript";
tool.concat(" is Awesome."); //returns "JavaScript is Awesome."
tool.concat(" Hello", " World"); //returns "JavaScript Hello World"
如你所見,該方法返回一個新的連接字符串,如果需要,你可以將多個字符串傳遞給它。
3. split() 方法
JavaScript 中的 split() 方法允許我們將字符串拆分為數組。 它使我們能夠在 JavaScript 中將字符串轉換為數組。
下面是一個例子:
const str = "JavaScript is Awesome";
//convert to an array of single characters.
str.split("");
// returns ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t", " ", "i", "s", " ", "A", "w", "e", "s", "o", "m", "e"]
//convert to an array of words.
str.split(" "); //returns ["JavaScript", "is", "Awesome"]
//get the first two words inside an array.
str.split(" ", 2); //returns ["JavaScript", "is"]
如你所見,該方法最多可以接受兩個參數,允許你按照自己的方式將字符串拆分為數組。
4. includes() 方法
includes() 方法檢查字符串是否包含作為方法參數傳遞的另一個特定字符串。 如果是,則返回 true 。 否則,它返回 false 。
這是示例:
const str = "JavaScript is Awesome";
str.includes("JavaScript"); //returns true
str.includes("Python"); //returns false
5. charCodeAt() 方法
charCodeAt()方法返回字符串中指定字符的 Unicode 編號。
你只需將要獲取其 Unicode 的字符的索引作為參數傳遞給該方法。
下面是一個例子:
const str = "JavaScript is Awesome";
str.charCodeAt(0); //returns 74
str.charCodeAt(2); //returns 118
如上所示,該方法返回指定字符的 Unicode 值。 當我們將 0 作為參數傳遞時,它返回字符串中第一個字母的 Unicode 值,即 Unicode 值為 74 的字母“J”。另一方面,當我們將 2 作為參數傳遞時,它返回 118,因為字母“v”的 Unicode 值為 118。
6. fromCharCode()方法
fromCharCode() 方法允許我們將 Unicode 值轉換為人類可以閱讀的可讀字符。 由於此方法是 String 對象的一部分,我們使用關鍵字 String 訪問它。
下面是一個例子:
String.fromCharCode(77); //returns "M"
String.fromCharCode(65); //returns "A"
String.fromCharCode(74, 65, 118, 65); //returns "JAVA"
如果你想使用 JavaScript 將字符串從二進制轉換為普通文本,則此方法非常有用。
7. replaceAll()方法
replaceAll() 方法是 ES2020 的新方法。 它允許我們將參數傳遞的另一個特定字符串替換一個字符串的多個實例。
我們可以使用普通字符串或全局正則表達式來替換所有實例。 你甚至可以傳遞一個函數來操作所有實例。
replaceAll()方法接受兩個參數:
- 要替換的字符串的實例。
- 將替換實例的字符串(你也可以傳遞普通字符串或函數)。
下面是一個例子:
const str = "Hello Hello JavaScript";
str.replaceAll(/Hello/g, "Hi"); //returns "Hi Hi JavaScript"
str.replaceAll("Hello", "Hi"); //returns "Hi Hi JavaScript"
str.replaceAll("Hello", (i) => i + " World");
//returns "Hello World Hello World JavaScript"
因此,該方法返回一個包含我們替換的所有新實例的新字符串。
數組操作技巧
1. 數組 find 簡化
當我們有一個對象數組,並想根據對象屬性找到特定對象,find 方法會非常有用。
const data = [{
type: 'test1',
name: 'abc'
},
{
type: 'test2',
name: 'cde'
},
{
type: 'test1',
name: 'fgh'
},
]
function findtest1(name) {
for (let i = 0; i < data.length; ++i) {
if (data[i].type === 'test1' && data[i].name === name) {
return data[i];
}
}
}
//Shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); // { type: 'test1', name: 'fgh' }
2. 快速調整大小和清空數組
編程時我們經常需要更改或清空數組。執行此操作的最有效方法是使用Array.length方法。
const array = [1,2,3,4,5];
console.log(array); // 5
array.length--;
console.log(array); // 4
array.length + = 15;
console.log(array); // 19
該代碼段的輸出為:
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 3, 4, ..15 empty]
undefined
你還可以通過將長度設置為0來刪除數組的所有元素。
let arr= ['a', 'b', 'c'];
arr.length = 0;
console.log(arr.length); // Ouput=> 0
console.log(arr); // Output=> []
3. 查找數組的最大值和最小值
const arr = [1, 2, 3];
Math.max(…arr); // 3
Math.min(…arr); // 1
4. 從數組中刪除重復項
你可以通過將數組轉換為集合,然后將集合中的值添加回數組來刪除數組的重復項。
這是有效的,因為集合是唯一的項目集合。
換句話說,一個集合中不能有兩個相同的值。因此,將數組轉換為集合會刪除引擎蓋下的重復項。
例如:
const nums = [1,1,1,1,3,4,5]
const uniqueNums = [...new Set(nums)];
這是實現其效果的另一種方法:
const nums = [1,1,1,1,3,4,5]
const uniqueNums = Array.from(new Set(nums))
5. 轉換為數組
這個簡單的代碼片段方法會將你的非數組值或數據轉換為數組形式。
const convertToArray = val => (Array.isArray(val) ? val : [val]);
convertToArray("Pro") // [Pro]
convertToArray(101) // [101]
17個JavaScript 數組方法
1、 Array.find()
使用.find()方法查找滿足條件的數組的第一個元素。例如,讓我們在汽車列表中找到第一輛經濟實惠的汽車:
const cars = [
{brand: "Porsche", price: 105000},
{brand: "BMW", price: 32000},
{brand: "Skoda", price: 15000},
{brand: "Toyota", price: 11500}
];
const affordableCar = cars.find(car => car.price <= 20000);
console.log(affordableCar)
輸出:
{
brand:"Skoda",
price:15000
}
2、Array.concat()
你可以使用.concat()方法將兩個或多個數組合並在一起。例如:
const nums1 = [1,2,3];
const nums2 = [4,5,6];
const merged = nums1.concat(nums2);
console.log(merged);
3、 Array.findIndex()
使用.findIndex()方法獲取第一個滿足條件的元素的索引。例如,讓我們找到列表中的第一個數字 3:
const nums = [1,2,3,3,3,2,1]
const idx = nums.findIndex( num => num == 3 )
console.log(idx)
輸出:
2
如果不存在與條件匹配的此類元素,則該.findIndex()方法返回-1。
4、Array.forEach()
這個超級好用,它可以讓你擺脫有時可能合適的常規 for 循環。
正如其名稱.forEach()表明,它被用於執行一個動作的陣列的每個元件。例如,讓我們打印數組的所有數字:
const nums = [1, 2, 3];
nums.forEach( num => console.log(num) );
輸出:
1
2
3
5、 Array.join()
你可以使用該.join()方法連接一組字符串以形成一個字符串。
例如,讓我們將單詞合並成一個句子。要形成一個句子,你需要用空格分隔每個單詞。這可以通過將空格作為參數傳遞給.join()方法來完成:
const words = ["This", "is", "a test"];
const sentence = words.join(" "); // separate words by blank spaces
console.log(sentence)
輸出:
This is a test
6、 Array.map()
你可以使用.map()方法對每個元素執行一個操作(即運行一個函數)並將結果放入一個新數組中。
例如,讓我們將一個數字數組轉換為一個新的平方數數組:
const nums = [1,2,3,4,5];
const squaredNums = nums.map( number => number * number );
console.log(squaredNums);
輸出:
[1, 4, 9, 16, 25]
7、Array.reduce()
該.reduce()方法通過為數組的每個元素執行一個函數並累加結果,將數組縮減為單個值。
例如,讓我們計算數組中數字的總和:
const nums = [1,2,3,4,5,6];
const numSum = nums.reduce((sum, num) => sum + num);
console.log(numSum);
輸出:
21
如果你不熟悉 reduce,讓我們檢查一下上面的代碼。該.reduce()方法為你提供了兩個值:
- 第一個值是累積的“總”值。在這種情況下,它被稱為sum。隨着該.reduce()方法通過數字工作,該值逐漸增加。
- 第二個值是 reduce 操作的當前元素。在這種情況下,它被稱為num。
- 簡而言之,所有.reduce()要做的就是遍歷數組的每個元素,並將每個值添加到 中sum以獲得數字的總和。
請注意,.reduce()可以選擇采用初始值。例如,你可以出於某種原因開始計算以下數字的總和:
const nums = [1,2,3,4,5,6];
const numSum = nums.reduce((sum, num) => sum + num, 1000);
console.log(numSum);
輸出:
1021
8、 Array.flat()
當你有一個多維數組時,你可以使用該.flat()方法將其展平。例如:
const nums = [0,1,2,[3,4]];
console.log(nums.flat());
輸出:
[0, 1, 2, 3, 4]
你還可以指定要將數組維度壓縮到的深度。例如,讓我們將這個 4 維數組展平為 2 維:
const nums = [0, 1, 2, [[[[[3, 4]]]]]];
console.log(nums.flat(2));
輸出:
[0,1,2,[3,4]]
9、Array.push()
使用.push()方法將新項目添加到數組中。例如:
let nums = [1, 2, 3]
nums.push(4)
nums.push(5, 6)
console.log(nums)
輸出:
[1, 2, 3, 4, 5, 6]
10、 Array.pop()
使用方法刪除並返回數組的最后一個元素.pop()。例如:
let nums = [1, 2, 3, 4, 5, 6]
const lastNum = nums.pop()
console.log(`Removed ${lastNum}, now the numbers are ${nums}`)
輸出:
Removed 6, now the numbers are 1,2,3,4,5
11、 Array.shift()
要刪除數組的第一個元素,你可以使用 .shift() 方法。例如:
const nums = [1, 2, 3, 4];
const first = nums.shift();
console.log(nums);
console.log(first);
輸出:
[2, 3, 4]
1
12、 Array.unshift()
該.unshift()方法將元素添加到數組的開頭+ 返回數組的新長度。例如:
const nums = [1, 2, 3];
nums.unshift(4, 5);
console.log(nums);
輸出:
[4, 5, 1, 2, 3]
13、 Array.filter()
顧名思義,你可以根據條件過濾數組的元素。結果,在過濾元素所在的位置創建了一個新數組。
例如,讓我們從數字列表中過濾所有偶數:
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNums = nums.filter( num => num % 2 == 0);
console.log(evenNums);
輸出:
[2, 4, 6, 8, 10]
14、 Array.sort()
按.sort()原樣使用方法對字符串數組進行排序:
const fruits = ["Banana", "Apple", "Clementine"]
const sorted = fruits.sort()
console.log(sorted)
輸出:
["Apple", "Banana", "Clementine"]
請注意,你不能只.sort()按原樣對數字數組進行排序!相反,你必須為該.sort()方法提供一個比較函數,以便它知道如何對數字進行實際排序。
例如,讓我們按升序對數字列表進行排序:
const nums = [1, 2, 3, 4]
const sorted = nums.sort((a, b) => a - b)
console.log(sorted)
15、 Array.reverse()
要反轉數組,你可以簡單地使用該.reverse()方法。舉個例子:
const nums = [1, 2, 3, 4]
const reversed = nums.reverse()
console.log(reversed)
輸出:
[4, 3, 2, 1]
16、Array.every()
你可以使用.every()方法來檢查數組的每個元素是否都通過了條件。如果有,則該方法返回true,否則返回false。
例如,讓我們檢查是否所有人都餓了:
const moods = ["hungry", "hungry", "hungry"];
const allHungry = moods.every(mood => mood === "hungry");
console.log(allHungry);
輸出:
true
17、Array.some()
該.some()方法與前面的.every()方法類似。不同之處在於,如果數組中的一個或多個元素滿足條件,則.some()返回true,false否則返回。
例如,讓我們檢查是否所有人都餓了:
const moods = ["hungry", "sleepy", "thirsty"];
const someHungry = moods.some(mood => mood === "hungry");
console.log(someHungry);
輸出:
true
4個JavaScript中的?操作符
下文中的 nullish 代表 null 或者 undefined
1. ?? 操作符
在 JavaScript 中,??
操作符被稱為nullish
合並操作符。如果第一個參數不是 null/undefined
,這個運算符將返回第一個參數,否則,它將返回第二個參數。讓我們看一個例子。
null ?? 5 // => 5
3 ?? 5 // => 3
當為一個變量分配默認值時,JavaScript 開發人員傳統上依賴於邏輯 OR
操作符,如下所示。
var prevMoney = 1
var currMoney = 0
var noAccount = null
var futureMoney = -1
function moneyAmount(money) {
return money || `You currently do not own an account in the bank`
}
console.log(moneyAmount(prevMoney)) // => 1
console.log(moneyAmount(currMoney)) // => `You currently do not own an account in the bank`
console.log(moneyAmount(noAccount)) // => `You currently do not own an account in the bank`
console.log(moneyAmount(futureMoney))// => -1
上面我們創建了一個函數 moneyAmount
,負責返回用戶的當前余額。我們使用了 ||
操作符來識別沒有帳戶的用戶。當 money 為 0 或者 null 的時候都會返回在當前銀行沒有這個賬戶,但是實際上賬戶是可能為 0 的 。在上面的示例中, ||
操作符將 0 視為假值,因此識別不出來我們的用戶擁有一個 0 美元的帳戶。 讓我們通過使用 nullish 合並操作符來解決這個問題。
var currMoney = 0
var noAccount = null
function moneyAmount(money) {
return money ?? `You currently do not own an account in the bank`
}
moneyAmount(currMoney) // => 0
moneyAmount(noAccount) // => `You currently do not own an account in the bank`
總結: ??
操作符允許我們分配默認值,同時忽略像 0 和空字符串這樣的假值。
2. ??=
操作符
??=
又稱為邏輯 nullish 賦值操作符,與我們之前學到的內容密切相關。讓我們看看它們是如何聯系在一起的。
var x = null
var y = 5
console.log(x ??= y) // => 5
console.log(x = (x ?? y)) // => 5
只有當前值為 null 或 undefined 時,此賦值運算符才會分配新值。
上面的例子強調了這個操作符如何實質上是 nullish 賦值的語法糖。
接下來,讓我們看看這個操作符與默認參數的區別。
function gameSettingsWithNullish(options) {
options.gameSpeed ??= 1
options.gameDiff ??= 'easy'
return options
}
function gameSettingsWithDefaultParams(gameSpeed=1, gameDiff='easy') {
return {gameSpeed, gameDiff}
}
gameSettingsWithNullish({gameSpeed: null, gameDiff: null}) // => { gameSpeed: 1, gameDiff: 'easy' }
gameSettingsWithDefaultParams(null, null) // => { gameSpeed: null, gameDiff: null }
上面的函數處理空值的方式有一個顯著的不同。默認參數將使用 null 參數覆蓋默認值,nullish 賦值操作符不會。默認參數和 nullish 賦值都不會覆蓋未定義的值。
3. ?.
操作符
可選的鏈接操作符 ?.
允許開發人員讀取深度嵌套在一個對象鏈中的屬性值,而不必沿途顯式驗證每個引用。當引用為 null 時,表達式停止計算並返回 undefined
,讓我們來看一個例子。
var travelPlans = {
destination: 'DC',
monday: {
location: 'National Mall',
budget: 200
}
};
const tuesdayPlans = travelPlans.tuesday?.location;
console.log(tuesdayPlans) // => undefined
現在,讓我們把迄今為止所學到的一切結合起來,把星期二添加到我們的新旅行計划中去吧!
function addPlansWhenUndefined(plans, location, budget) {
if (plans.tuesday?.location === undefined) {
var newPlans = {
plans,
tuesday: { location: location ?? "Park", budget: budget ?? 200 },
};
} else {
newPlans ??= plans; //will only override if newPlans is undefined
console.log("Plans have already been added!");
}
return newPlans;
}
var newPlans = addPlansWhenUndefined(travelPlans, "Ford Theatre", null);
console.log(newPlans) // => { plans:
//{ destination: 'DC',
// monday: { location: 'National Mall', budget: 200 } },
// tuesday: { location: 'Ford Theatre', budget: 200 } }
newPlans = addPlansWhenUndefined(newPlans, null, null) // logs => Plans have already been added!
// returns => newPlans object
我們現在已經創建了一個函數,該函數將計划添加到當前沒有嵌套屬性 tuesday.location
的對象中。我們還使用 nullish 操作符提供默認值。這個函數將接受錯誤的值,如“0”作為有效的參數。這意味着我們的預算可以設置為零,沒有任何錯誤。
4. ?
操作符
三元運算符 ?
有三個操作數: 一個條件,一個條件為真時執行的表達式,以及一個條件為假時執行的表達式。讓我們看看它是如何運作的。
function checkCharge(charge) {
return (charge > 0) ? 'Ready for use' : 'Needs to charge'
}
console.log(checkCharge(20)) // => 'Ready for use'
console.log(checkCharge(0)) // => 'Needs to charge'
如果你花了一些時間研究 JavaScript,你可能以前見過三元運算符。然而,你知道三元運算符可以用於變量賦值嗎?
var budget = 0
var transportion = (budget > 0) ? 'Train' : 'Walking'
console.log(transportion) // => 'Walking'
我們甚至可以用它來復制 nullish 賦值的行為。
var x = 6
var x = (x !== null || x !== undefined) ? x : 3
console.log(x) // => 6
現在讓我們通過創建一個函數來泛化這種行為!
function nullishAssignment(x,y) {
return (x == null || x == undefined) ? y : x
}
var x = nullishAssignment(null, 8) // => 8
var y = nullishAssignment(4,8) // => 4
在結束之前,讓我們使用三元運算符來重構前面示例中的函數。
function addPlansWhenUndefined(plans, location, budget) {
var newPlans =
plans.tuesday?.location === undefined
? {
...plans,
tuesday: { location: location ?? "Park", budget: budget ?? 200 },
}
: console.log("Plans have already been added!");
newPlans ??= plans;
return newPlans;
}
6個JavaScript對象操作方法
1. Object.entries()
這個方法可以將對象轉換為對象數組。
const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/
2. Object.values()
這也是 ES8 中引入的一個新特性,它的功能類似於 Object.entries(),只是沒有鍵。
const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
3. Object.keys()
還記得那些痛苦的日子,你不得不手動迭代一個對象來獲取它的鍵,然后執行一些乏味的邏輯......我只是想想就覺得累了。
但是,幸運的是,我們有一個簡潔的小方法,可以通過單行代碼為我們解決問題:
let cat = {
name: 'Jimmy boy',
age: 5,
breed: 'British Shorthair',
favorite_word: 'Meow',
favorite_food: 'Chimkens'
}
console.log(Object.keys(cat)); // [ 'name', 'age', 'breed', 'favorite_word', 'favorite_food' ]
Object.keys 返回一個數組,我們可以迭代它並使用這些鍵做任何我們需要做的事情。
4. Object.freeze( )
該方法Object.freeze( )防止對象中的數據突變(鎖定對象數據)。因此,你不能將Object.freeze( )作為參數傳遞給對象,更不能添加,更新或刪除屬性。
看下面的例子:
const employee = {
name: "James",
age: 25,
available: true
}
//Freezing the object.
Object.freeze(employee);
//updating and adding properties.
employee.name = "Brad";
employee.newProp = "Hard Worker";
console.log(employee);
//Output: {name: "James", age: 25, available: true}
如你所見,即使我們更新了屬性,該對象也不會更改。
5. Object.seal( )
該方法Object.seal( )有點類似於Object.freeze( )。它可以防止向對象添加新屬性,但是可以更改和更新現有屬性。
const user = {
name: "Alex",
age: 23,
isOnline: false
}
//使用Object.seal()
Object.seal(user);
//更新屬性。
user.isOnline = true;
//添加一個屬性。
user.active = false;
console.log(user);
//輸出:{名稱:“ Alex”,年齡:23,isOnline:true}
該屬性isOnline已更新,但是我們無法將該屬性添加active到對象中,因為我們使用Object.seal( )它來防止這種情況的發生。
6. Object.create( )
該方法Object.create()用於從另一個現有對象的原型創建一個新對象。
看下面的例子:
const user = {
firstName: "John",
lastName: "Doe",
age: 25,
fullName(){
return `${this.firstName} ${this.lastName}`;
}
}
//新對象。
let newObject = Object.create(user);
//更新屬性。
newObject.firstName = "Mehdi";
newObject.lastName = "Aoussiad";
//我們也可以在此新對象中使用user的fullName方法。
newObject.fullName(); //輸出:Mehdi Aoussiad
console.log(newObject);
//輸出:{firstName:“ Mehdi”,lastName:“ Aoussiad”}
在上面的示例中,我們用於Object.create()創建一個具有用戶對象原型的新對象。這就是為什么我們能夠更改屬性並user在新對象中使用對象的方法的原因。如果你不想在對象中復制代碼,這將非常有用。
函數相關
箭頭函數
//Longhand
function add(a, b) {
return a + b;
}
//Shorthand
const add = (a, b) => a + b;
更多例子:
function callMe(name) {
console.log('Hello', name);
}
callMe = name => console.log('Hello', name);
隱式返回
通過使用箭頭函數,我們可以直接返回值,不需要 return 語句。
//longhand
function calculate(diameter) {
return Math.PI * diameter
}
//shorthand
calculate = diameter => (
Math.PI * diameter;
)
簡短的函數調用
我們可以使用三元操作符來實現多個函數調用。
// Longhand
function test1() {
console.log('test1');
};
function test2() {
console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
test1();
} else {
test2();
}
// Shorthand
(test3 === 1? test1:test2)();
for循環
// 一個這個大的數組
var array = []
array.length = 10000000
var array = []
array.length = 10000000
console.time('for++')
for (let i = 0; i < array.length; i++) {
}
console.timeEnd('for++') // 7.009033203125 ms
console.time('for--')
for (let i = array.length; i > 0; i--) {
}
console.timeEnd('for--') // 6.798828125 ms
console.time('forEach')
array.forEach(function () {
})
console.timeEnd('forEach') // 25.0791015625 ms
console.time('forOf')
for (let i of array) {
}
console.timeEnd('forOf') // 174.65478515625 ms
正序常規for循環
for (let i = 0; i < array.length; i++) {
}
倒敘常規for循環
for (let i = array.length; i > 0; i--) {
}
forEach
array.forEach(function () {
})
for ... of ...
for...of是在ES6(ECMAScript中6)中實現標准化的。它會基於一個可迭代對象,比如array,map,set,string等創建一個循環,並且擁有更優秀的可讀性。
for (const i of array) {
}
for ... in...
在for...in對象的所有可以列舉出來的屬性上迭代指定的變量。對於每個不同的屬性,for...in語句除返回數字索引外,還將返回用戶定義的屬性的名稱。
for (const i in array) {
}
for..of和for...in之間的主要區別是它們迭代的內容。上面所說的for...in環路迭代的是對象的屬性,而for...of循環遍歷一個迭代對象的值。
其他
指數表示法
// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) {
默認參數值
//Longhand
function add(test1, test2) {
if (test1 === undefined)
test1 = 1;
if (test2 === undefined)
test2 = 2;
return test1 + test2;
}
//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2);
add() //output: 3
模板字面量
如果你厭倦了使用 + 將多個變量連接成一個字符串,那么這個簡化技巧將讓你不再頭痛。
//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
//shorthand
const welcome = `Hi ${test1} ${test2}`;
跨行字符串
當我們在代碼中處理跨行字符串時,可以這樣做。
//longhand
const data = 'abc abc abc abc abc abc\n\t'
+ 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
test test,test test test test`
將字符串轉成數字
//Longhand
let test1 = parseInt('123');
let test2 = parseFloat('12.3');
//Shorthand
let test1 = +'123';
let test2 = +'12.3';
indexOf 的按位操作簡化
在查找數組的某個值時,我們可以使用 indexOf() 方法。但有一種更好的方法,讓我們來看一下這個例子。
//longhand
if(arr.indexOf(item) > -1) { // item found
}
if(arr.indexOf(item) === -1) { // item not found
}
//shorthand
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}
按位 (~) 運算符將返回 true(-1 除外),反向操作只需要!~。另外,也可以使用 include() 函數。
if (arr.includes(item)) {
// true if the item found
}
雙重按位操作/Math.floor() 簡寫
// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true
重復字符串多次
為了重復操作相同的字符,我們可以使用 for 循環,但其實還有一種簡便的方法。
//longhand
let test = '';
for(let i = 0; i < 5; i ++) {
test += 'test ';
}
console.log(str); // test test test test test
//shorthand
'test '.repeat(5);
獲取字符串的字符
let str = 'abc';
//Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c
指數冪簡化/ Math.pow() 簡寫
//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8
將任何值轉換為布爾值
在 JavaScript 中,你可以將任何內容轉換為布爾值。這是因為,在底層,JavaScript 中的一切要么是“True”,要么是“False”。
要將任何內容轉換為布爾值,請使用雙感嘆號 !!。
例如:
!!true // true
!!2 // true
!![] // true
!!"Test" // true
!!false // false
!!0 // false
!!"" // false
字節大小
此代碼段將顯示你的字符串或整數的字節大小。簡單來說,它會顯示字符串或整數的長度。
const byteSize1 = str => new Blob([str]).size;
const byteSize2 = int => new Blob([int]).size;
byteSize1("JavaScript") // 10
byteSize2(101) // 3
大寫
此代碼段方法將以大寫形式轉換字符串中字符的每個第一個字母。檢查下面的代碼以了解它是如何工作的。
const capitalize = str =>
str.replace(/\b[a-z]/g, char => char.toUpperCase());
capitalize('code'); //Code
capitalize('javascript programming'); //Javascript Programming
數字化
這個是很棒的片段,它會將你的數字轉換為數字數組。查看下面的代碼示例。
const digitize = n => [...`${n}`].map(i => parseInt(i));
digitize(345) // [3,4,5]
digitize(123) // [1,2,3]
digitize(6) // [6]
isUpper Case
當你想檢查 String 是否為大寫時,此片段代碼將很有用。
const isUpperCase = str => str === str.toUpperCase();
isUpperCase("Code") //false
isUpperCase("PROGRAMMING") //true
isUpperCase("aB") //false
isLower Case
我們看到的這個大寫片段代碼將檢查字符串是否為小寫。
const isLowerCase = str => str === str.toLowerCase();
isLowerCase("code") //true
isLowerCase("PROGRAMMING") //false
范圍生成器中的整數數組
這段代碼將向你展示如何生成一個帶有n數字且在一個范圍內的隨機整數數組。檢查下面的代碼以了解它是如何工作的。
const randomIntArrayInRange = (min, max, n = 1) =>
Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
console.log(randomIntArrayInRange(10, 15, 5)); // [ 14, 11, 15, 10, 13 ]
范圍生成器中的隨機整數
此片段代碼用於生成給定范圍內的隨機整數。
const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInteger(1,10)) // 6
console.log(randomInteger(1,20)) // 8
從列表中刪除 False 元素
此代碼段方法將從列表中刪除 false 元素,如 null、false、0 或空元素。
const compactJs = arr => arr.filter(Boolean);
compactJs([2,4,false,NaN,5,"",0]) //[2,4,5]