JavaScript : Tricks You Should Know(你应该知道的技巧)
The ternary operator(三元运算符)
Noobs:
let hungry = true;
let eat;
if (hungry === true) {
eat = 'yes';
} else {
eat = 'no';
}
Pro:
let hungry = true;
let eat = hungry === true ? 'yes' : 'no';
Number to string / string to number(数字转字符串/字符串转数字)
Noobs:
let num = 15;
let s = num.toString(); // number to string
let n = Number(s); // string to number
Pro:
let num = 15;
let s = num + ""; // number to string
let n = +s; // string to number
Dynamic properties in objects(对象的动态属性)
Noobs:
let dynamic = "value";
let user = {
id: 1,
};
user[dynamic] = "other value";
Pro:
let dynamic = "value";
let user = {
id: 1,
[dynamic]: "other value"
};
Removing duplicates(删除重复项)
Noob:
let array = [100, 23, 23, 23, 23, 67, 45];
let outputArray = [];
let flag = false;
for (j = 0; < array.length; j++) {
for (k = 0; k < outputArray.length; k++) {
if (array[j] == outputArray[k]) {
flag = true;
}
}
if (flag == false) {
outputArray.push(array[j]);
}
flag = false;
}
//outputArray = [100, 23, 67, 45]
Pro:
let array = [100, 23, 23, 23, 23, 67, 45];
let outputArray = Array.from(new Set(array));
//outputArray = [100, 23, 67, 45]
Array to object(数组到对象)
Noob:
let arr = ["value1", "value2", "value3"];
let arrObject = {};
for (let i = 0; i < arr.length; ++i) {
if (arr[i] !== undefined) {
arrObject[i] = arr[i];
}
}
Pro:
let arr = ["value1", "value2", "value3"];
let arrObject = {...arr};
Object to Array(对象到数组)
Noob:
let number = {
one: 1,
two: 2,
};
let keys = [];
for (let numbers in numbers) {
if (number.hasOwnProperty(number)) {
keys.push(number);
}
}
// key = [ 'one', 'two' ]
Pro:
let numbers = {
one: 1,
two: 2,
};
let key = Object.keys(numbers); // key = [ 'one', 'two' ]
let value = Object.values(numbers); // value = [ 1, 2 ]
let entry = Object.entries(numbers); // entry = [['one' : 1], ['two' : 2]]
Short circuit conditionals(短路条件)
Noob:
if (docs) {
goToDocs();
}
Pro:
docs && goToDocs()
Use ^ to check if numbers are not equal(使用 ^ 检查数字是否不相等)
if(a!=123) // before // NOOBS
if(a^123) // after // PRO
Loop over an object(循环遍历对象)
const age = {
Rahul: 20,
max: 16
};
// Solution 1 - Get 'keys' and loop over
const keys = Object.keys(age);
keys.forEach(key => age[key]++);
console.log(age); // { Rahul: 21, max: 17 }
// Solution 2 - for ..in loop
for(let key in age){
age[key]++;
}
console.log(age); // { Rahul: 22, max: 18 }
Object keys are stored in insertion order(对象键按插入顺序存储)
const obj = {
name: "Rahul",
age: 16,
address: "Earth",
profession: "Developer",
};
console.log(Object.keys(obj)); // name, age, address, profession
Check if value is an array(检查值是否是数组)
const arr = [1, 2, 3];
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true
Initialize an array of size n and fill with default values(初始化大小为 n 的数组并填充默认值)
const size = 5;
const defaultValue = 0;
const arr = Array(size).fill(defaultValue);
console.log(arr); // [0, 0, 0, 0, 0]
Truthy and False values(真假价值观)
False values => false
,0
,""
(empty string), null
, undefined
, &NaN
.
Truthy values => "Values"
, "0"
, {}
(empty object), &[]
(empty array)
Difference between double equal and triple equal(双等号和三等号的区别)
// Double equal - Converts both the operands to the same type and then comapares
console.log(0 == '0'); // true
// Triple Equal - Does not convert t same type
console.log(0 === '0'); // false
Better way to accept arguments(接受论点的更好方法)
function downloadData(url, resourceId, searchTest, pageNo, limit) {}
downloadData(...); // need to remember the order
Simpler way to do:
function downloadData(
{ url, resourceId, searchTest, pageNo, limit } = {}
) {}
downloadData(
{ resourceId: 2, url: "/posts", searchText: "WebDev" }
);
null vs undefined
null => It is a value whereas undefined is not.
null is like an empty box and undefined it not box at all.
const fn = (x = 'default value') => console.log(x);
fn(undefined); // default value
fn(); // default value
fn(null); // null
When null is passed, the default value is not taken. Whereas, when undefined or nothing is passed the default value is taken.
当传递 null 时,不会使用默认值。而当传递未定义值或空值时,则使用默认值。
【参考文献】
标题:17 Pro JavaScript tricks you didn’t know
作者:Xiuer Old
日期:7月3日
上述译文仅供参考,原文请查看下面链接,解释权归原作者所有
⚠️:文章翻译如有语法不准确或者内容纰漏,欢迎评论区指正。
【关于TalkX】
TalkX是一款基于GPT实现的IDE智能开发插件,专注于编程领域,是开发者在日常编码中提高编码效率及质量的辅助工具,TalkX常用的功能包括但不限于:解释代码、中英翻译、性能检查、安全检查、样式检查、优化并改进、提高可读性、清理代码、生成测试用例等。
TalkX建立了全球加速网络,不需要考虑网络环境,响应速度快,界面效果和交互体验更流畅。并为用户提供了OpenAI的密钥,不需要ApiKey,不需要自备账号,不需要魔法。
TalkX产品支持:JetBrains (包括 IntelliJ IDEA、PyCharm、WebStorm、Android Studio)、HBuilder、VS Code、Goland.