给初级 JavaScript 开发者的 18 个技巧
1. 转换为字符串
const input = 123;
console.log(input + ''); // '123'
console.log(String(input)); // '123'
console.log(input.toString()); // '123'
2. 转换为数字
const input = '123';
console.log(+input); // 123
console.log(Number(input)); // 123
console.log(parseInt(input)); // 123
3. 转换为布尔值
const input = 1;
// Solution 1 - Use double-exclamation (!!) to convert to boolean
console.log(!!input); // true
// Solution 2 - Pass the value to Boolean()
console.log(Boolean(input)); // true
4. 字符串问题'false'
const value = 'false';
console.log(Boolean(value)); // true
console.log(!!value); // true
// The best way to check would be,
console.log(value === 'false');
5. null 与 undefined
null
是一个值,而undefined
不是。null
就像一个空盒子,而undefined
根本不是盒子。
例如,
const fn = (x = 'default value') => console.log(x);
fn(undefined); // default value
fn(); // default value
fn(null); // null
当null
传递时,不采用默认值,而当undefined
或未传递任何内容时,则采用默认值。
6. 真值和假值
虚假值- false
,,(空字符串0
),,,& 。""
null
undefined
NaN
真值- "false"
,,"0"
({}
空对象),& []
(空数组)
7. 可以进行哪些更改const
const
用于值不变的情况。例如,
const name = 'Codedrops';
name = 'Codedrops.tech'; // Error
const list = [];
list = [1]; // Error
const obj = {};
obj = { name: 'Codedrops' }; // Error
但它可以用来更新先前分配的数组/对象引用中的值
const list = [];
list.push(1); // Works
list[0] = 2; // Works
const obj = {};
obj['name'] = 'Codedrops'; // Works
8. 双等号和三等号的区别
// Double equal - Converts both the operands to the same type and then compares
console.log(0 == '0'); // true
// Triple equal - Does not convert to same type
console.log(0 === '0'); // false
9. 更好地接受论点
function downloadData(url, resourceId, searchText, pageNo, limit) {}
downloadData(...); // need to remember the order
更简单的方法是-
function downloadData(
{ url, resourceId, searchText, pageNo, limit } = {}
) {}
downloadData(
{ resourceId: 2, url: "/posts", searchText: "programming" }
);
10. 将普通函数重写为箭头函数
const func = function() {
console.log('a');
return 5;
};
func();
可以重写为
const func = () => (console.log('a'), 5);
func();
11. 从箭头函数返回对象/表达式
const getState = (name) => ({name, message: 'Hi'});
12. 将集合转换为数组
const set = new Set([1, 2, 1, 4, 5, 6, 7, 1, 2, 4]);
console.log(set); // Set(6) {1, 2, 4, 5, 6, 7}
set.map((num) => num * num); // TypeError: set.map is not a function
要转换为数组,
const arr = [...set];
13. 检查值是否为数组
const arr = [1, 2, 3];
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true
14. 对象键按插入顺序存储
const obj = {
name: "Human",
age: 0,
address: "Earth",
profession: "Coder",
};
console.log(Object.keys(obj)); // name, age, address, profession
Objects
保持密钥的创建顺序。
15. 空值合并运算符
const height = 0;
console.log(height || 100); // 100
console.log(height ?? 100); // 0
Nullish coalescing operator
(??)仅当左侧值为undefined
或时才返回右侧值null
16. 地图()
它是一个实用函数,用于将函数应用于数组的每个元素。
它返回一个新数组,其中包含从该应用函数返回的值。例如,
const numList = [1, 2, 3];
const square = (num) => {
return num * num
}
const squares = numList.map(square);
console.log(squares); // [1, 4, 9]
这里,该函数square
应用于每个元素,即 1、2、3。
该函数的返回值作为新元素值返回。
17. try..catch..finally - 真实示例
const getData = async () => {
try {
setLoading(true);
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
// if error occurs here, then all the statements
//in the try block below this wont run.
// Hence cannot turn off loading here.
const data = await response.json();
setData(data);
} catch (error) {
console.log(error);
setToastMessage(error);
} finally {
setLoading(false); // Turn off loading irrespective of the status.
}
};
getData();
18.解构
const response = {
msg: "success",
tags: ["programming", "javascript", "computer"],
body: {
count: 5
},
};
const {
body: {
count,
unknownProperty = 'test'
},
} = response;
console.log(count, unknownProperty); // 5 'test'
感谢阅读💙
关注@codedrops.tech获取每日更新
。Instagram ● Twitter ● Facebook
微学习 ● Web 开发 ● Javascript ● MERN 堆栈 ● Javascript
codedrops.tech