做为一名开发人员,工做以外的时间老是在学习新事物。做为前端开发人员必须知道一些使咱们的代码如何更优雅,工做更轻松的技巧,让本身的代码写的更加高大上,下面这些技巧获取能够帮助到你。前端
// long
if( x === 'a' || x === 'b' || x === 'c' || x === 'd'){
// todo
}
// short
if(['a', 'b', 'c', 'd'].includes(x)){
// todo
}
当咱们仅使用一些一对if/esle条件判断时, 能够简单地使用三元运算符来实现. 如有多对if/else条件判断,则不建议使用web
// long
let flag
if(x > 10){
flag = true
}else {
flag = false
}
// short
let flag = x > 10 ? true : false
当咱们要声明两个具备共同值或共同类型的变量时,能够使用此简写形式编程
// long
let a
let b = 1
// short
let a, b = 1
当咱们须要建立新变量时, 有时须要检查为其值引用的变量是否为null
或undefined
, 能够考虑以下实现:数组
// long
if(test1 !== null || test1 !== undefined || test1 !== ""){
let test2 = test1;
}else {
let test2 = ''
}
// short
let test2 = test1 || ''
当咱们处理多个变量并但愿将不一样的值分配给不一样的变量时,此法很是有用。编辑器
//long
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Short
let [test1, test2, test3] = [1, 2, 3];
咱们在编程中处理不少算术运算符。这是将运算符分配给JavaScript变量的有用技术之一函数
// long
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// short
test1++;
test2--;
test3 *= 20;
// long
if (test1 === true)
// short
if (test1)
//long
if (test1) {
callMethod();
}
//short
test1 && callMethod();
// long
for (var i = 0; i < testList.length; i++)
// short
testList.forEach(item => console.log(item))
// long
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);
}
// short
function checkReturn() {
return test || callMe('test');
}
//long
function add(a, b) {
return a + b;
}
//short
const add = (a, b) => a + b;
// long
function test1() {
console.log('test1');
};
function test2() {
console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
test1();
} else {
test2();
}
// short
(test3 === 1? test1:test2)();
咱们能够将条件保存在键值对象中,并能够根据条件使用。学习
// long
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
// short
var data = {
1: test1,
2: test2,
3: test
};
data[something] && data[something]();
//long
function add(test1, test2) {
if (test1 === undefined)
test1 = 1;
if (test2 === undefined)
test2 = 2;
return test1 + test2;
}
//short
add = (test1 = 1, test2 = 2) => (test1 + test2);
add() //output: 3
// long
function hello(obj){
let {name, age} = obj
if(!name){
console.warn('name is null, pls check!')
return ''
}
if(!age){
console.warn('age is null, pls check!')
return ''
}
return `${name}: ${age}`
}
// short
function hello(obj){
let {name = required('name'), age = required('age')} = obj
return `${name}: ${age}`
}
function required(key){
console.warn(`${key} is null, pls check!')
}
//long
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
//short
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]
对于克隆, 咱们也能够使用扩展运算符ui
//long
const test1 = [1, 2, 3];
const test2 = test1.slice()
//short
const test1 = [1, 2, 3];
const test2 = [...test1];
若是您厌倦了在单个字符串中使用+来链接多个变量,能够考虑用这种方式url
//long
const welcome = 'Hi ' + user + ' ' + name + '.'
//short
const welcome = `Hi ${user} ${name}`;
let test1 = 'a';
let test2 = 'b';
//Long
let obj = {test1: test1, test2: test2};
//short
let obj = {test1, test2};
//Long
let test1 = parseInt('123');
let test2 = parseFloat('12.3');
//Short
let test1 = +'123';
let test2 = +'12.3';
当咱们确实有一个对象数组而且咱们想要根据对象属性查找特定对象时,find
方法确实颇有用。spa
const data = [{
type: 'test1',
name: 'abc'
},
{
type: 'test2',
name: 'cde'
},
{
type: 'test1',
name: 'fgh'
},
]
// long
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);
若是咱们有代码来检查类型,而且基于类型须要调用不一样的方法,咱们能够选择使用多个else if或进行切换,有没有更好的呢?
// long
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);
}
// short
const types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};
let func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();
当咱们迭代数组以查找特定值时,咱们确实使用indexOf()
方法,若是咱们找到更好的方法呢?让咱们看看这个例子。
//long
if(arr.indexOf(item) > -1) { // item found
}
if(arr.indexOf(item) === -1) { // item not found
}
//short
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}
按位~运算符
将返回非-1的真实值。取反就像作~同样简单。另外,咱们也能够使用include()
函数:
if (arr.includes(item)) {
// true if the item found
}
此功能有助于将对象转换为对象数组
const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** ouput
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/
const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
要一次又一次地重复相同的字符,咱们能够使用for
循环并将它们添加到同一循环中,可是若是咱们有一个简写方法呢?
//long
let test = '';
for(let i = 0; i < 5; i ++) {
test += 'test ';
}
console.log(str); // test test test test test
//short
'test '.repeat(5);
const arr = [1, 2, 3]; Math.max(…arr); // 3Math.min(…arr); // 1