書上不教但非常實用的JavaScript實踐
我是通過看視頻、上網(wǎng)課和讀文章來學(xué)習(xí)JavaScript的。
在學(xué)習(xí)和實踐過程中,我發(fā)現(xiàn)有些東西雖然在課程中沒有得到明確的教授和解釋,但卻被開發(fā)人員大量使用。
因此,為了幫助JavaScript初學(xué)者在掌握基礎(chǔ)知識后,能更靈活自如地運用JS知識,我寫了這篇文章。
一起來看看吧!
短路運算符
console.log(true || 'something') // 'true' returns left side expression on the truthy value
console.log(null || 'something') // 'something'
console.log(true && 'somethingNew') // 'something' returns right side expression on the truthy value
console.log(null && 'somethingNew') // 'null' returns left side on falsy value
// nullish operator returns right side only if null or undefined value is on left otherwise it returns right
console.log(null ?? 'printA')
console.log(undefined ?? 'printB')
console.log(false ?? 'printB')
console.log(true ?? 'printB')
//assignment operator
const rest1 = {
owner: 'Jonas',
rooms : 15,
available : true,
}
const rest2 = {
owner: 'Max',
rooms : 12,
available : false,
booked : 'Yes'
}
rest1.available &&= 'booking done'
rest2.available &&= 'booking done'
console.log(rest1.available) // 'booking done'
console.log(rest2.available) // 'false'
rest1.booked &&= 'yes'
console.log(rest1.booked) //undefined
rest1.booked ||= 'yes'
console.log(rest1.booked) // 'yes'
rest2.address ??= 'calfornia'
console.log(rest2.address) // 'calfornia' so basically ??= assign the value if not present
rest2.booked ??= 'No'
console.log(rest2.booked) 'Yes' //since the value was already present therefore this No was not updated
可選鏈接 ?.
可選鏈接這項JavaScript中的功能,簡化了當(dāng)屬性或方法可能不存在時,訪問對象上的屬性或調(diào)用方法的過程。它可幫助防止錯誤、簡化對undefined或null值的條件檢查。
可選鏈接使用?.運算符。請看以下示例:
const person = {
name: 'John',
address: {
street: '123 Main St',
},
};
// Without optional chaining
const street = person.address ? person.address.street : undefined;
console.log(street); // '123 Main St'
// With Optional chaining
const street = person.address?.street;
console.log(street); // '123 Main St'
const car = {
startEngine: function () {
console.log('Engine started');
},
};
// Without optional chaining
if (car.startEngine) {
car.startEngine();
}
//with optional chaining
car.startEngine?.(); // 'Engine started'
還可以將可選鏈接與屬性訪問和方法調(diào)用結(jié)合到單個表達式中:
const user = {
profile: {
username: 'jsmith',
greet: function () {
console.log('Hello, ' + this.username);
},
},
};
const greeting = user.profile?.greet?.();
// If `profile` or `greet` are missing, `greeting` will be undefined.
for-of循環(huán)
JavaScript中的for… of循環(huán)用于遍歷可迭代對象,如數(shù)組、字符串、映射、集合等的值。與傳統(tǒng)的for和while循環(huán)相比,語法更簡潔、更干凈。以下是for… of循環(huán)示例:
const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
console.log(number);
}
// Output:
// 1
// 2
// 3
// 4
// 5
遍歷字符串示例
const text = "Hello, World!";
for (const char of text) {
console.log(char);
}
// Output:
// H
// e
// l
// l
// o
// ,
//
// W
// o
// r
// l
// d
// !
遍歷對象示例
const students = [
{ name: "Alice", age: 22 },
{ name: "Bob", age: 25 },
{ name: "Carol", age: 21 },
];
for (const student of students) {
console.log(student.name, student.age);
}
// Output:
// Alice 22
// Bob 25
// Carol 21
遍歷map
const myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
for (const [key, value] of myMap) {
console.log(key, value);
}
// Output:
// key1 value1
// key2 value2
遍歷set
const mySet = new Set([1, 2, 3, 2, 4]);
for (const item of mySet) {
console.log(item);
}
// Output:
// 1
// 2
// 3
// 4
還可以試試其他循環(huán),例如
const rest2 = {
owner: 'Max',
rooms : 12,
available : false,
booked : 'Yes'
}
console.log(Object.keys(rest2))
console.log(Object.values(rest2))
for (let prop of Object.keys(rest2)){
console.log(prop)
}
console.log(Object.entries(rest2))
for(let entry of Object.entries(rest2)){
console.log(entry)
}
Set
set是唯一數(shù)據(jù)值的集合。
語法如下所示:
const uniqueSet = new Set(['a','b','b','c','c'])
以下是一些set方法
const uniqueSet = new Set(['a','b','b','c','c'])
console.log(uniqueSet) //Set { 'a', 'b', 'c' }
console.log(uniqueSet.size) //3
console.log(uniqueSet.has('b')) //true
console.log(uniqueSet.has('d')) //false
uniqueSet.add('d')
console.log(uniqueSet.has('d')) //true
uniqueSet.delete('b')
console.log(uniqueSet.has('b')) //false
uniqueSet.clear()
console.log(uniqueSet.size)//0
const animalNames = ["dog", "cat", "lion", "elephant", "dog", "tiger", "cat", "giraffe", "monkey", "elephant"];
const uniqueAnimals = [...new Set(animalNames)];
console.log(uniqueAnimals) //
映射map
映射有點像具有鍵值對的對象,但有一個區(qū)別,在對象中,鍵始終是字符串類型,而在映射中,鍵可以具有任何類型。
const rest = new Map();
rest.set('name', 'Dwesis');
rest.set(1,'Prayagraj');
console.log(rest.get('name'))
console.log(rest.set(2, 'Ahmedabad'))
rest.set('categories',['italian','chinese','indian']).set('open',11).set('close',23).set(true,'We are open')
console.log(rest.get(true))
const rest = new Map([
['name', 'Dewsis'],
[true, 'We are open'],
[false, 'we are close'],
[1, 'Prayagraj'],
[2, 'Ahmedabad']
]
)
console.log(rest.get(true)) // 'We are open'
console.log(rest.get(false)) // 'we are close'
console.log(rest.has('open')) // true
console.log(rest.has('close')) // false
console.log(rest.has(3)) // false
console.log(rest.size) // 5
for (let [key,value] of rest){
console.log(`${key} : ${value}`)
}
//Output
//name : Dewsis
// true : We are open
// false : we are close
// 1 : Prayagraj
// 2 : Ahmedabad
數(shù)組 vs set,以及對象 vs Map
數(shù)組:
在以下情況下使用數(shù)組:
- 需要有序的元素集合。
- 需要對元素進行索引訪問。
- 想要存儲類似項目或相關(guān)項目的列表。
- 需要對元素執(zhí)行迭代、映射或縮減等操作。
例如:
const colors = ['red', 'green', 'blue'];
set:
在以下情況下使用set:
- 需要存儲沒有重復(fù)項的唯一值。
- 希望執(zhí)行諸如檢查是否存在之類的操作,或者執(zhí)行諸如并集、交集或差值之類的集合操作。
- 需要確保每個元素在集合中僅出現(xiàn)一次。
例如:
const uniqueNumbers = new Set([1, 2, 3, 4, 4, 5]);
對象:
在以下情況下使用對象:
- 需要存儲鍵值對,例如將唯一鍵映射到值。
- 希望使用屬性和方法表示實體或復(fù)雜數(shù)據(jù)結(jié)構(gòu)。
- 需要執(zhí)行基于鍵的數(shù)據(jù)檢索、修改或刪除等操作。
例如:
const person = {
name: 'John Doe',
age: 30,
email: 'johndoe@example.com'
};
map
在以下情況下使用map:
- 需要使用任意數(shù)據(jù)類型(包括對象)作為鍵。
- 需要可迭代的數(shù)據(jù)結(jié)構(gòu)來維護插入順序。
- 希望使用size屬性輕松確定map大小。
- 需要執(zhí)行添加或刪除元素、檢查鍵是否存在以及迭代鍵值對等操作。
例如:
const myMap = new Map();
const key1 = { id: 1 };
const key2 = { id: 2 };
myMap.set(key1, 'value1');
myMap.set(key2, 'value2');
當(dāng)你需要使用鍵值對、需要使用各種數(shù)據(jù)類型作為鍵、保持插入順序以及輕松管理數(shù)據(jù)結(jié)構(gòu)大小等時,Map非常有用。
希望這篇文章能對大家有所幫助。