Js几个最佳实践语法技巧

判断该值是否等于某个值(IE不兼容)

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    
    
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
    
    
   //logic
}

三元运算符避免冗长的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);

null、undefined 和空值检查

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    
    
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';

多变量赋值(IE不兼容)

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand 
let [test1, test2, test3] = [1, 2, 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)

用于多个条件判断的 && 操作符

//Longhand 
if (test1) {
    
    
 callMethod(); 
} 
//Shorthand 
test1 && callMethod();

foreach

// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or  for (let i of testData)

遍历数组的风骚技巧

function testData(element, index, array) {
    
    
            alert('test[' + index + '] = ' + element);
        }
        [11, 24, 32].forEach(testData);

判断空的if else

// 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');
}

箭头函数(IE不兼容)

//Longhand 
function add(a, b) {
    
     
   return a + b; 
} 
//Shorthand 
const add = (a, b) => a + b;

风骚的根据对应值调用对应函数技巧

// 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)();

避免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]();

简单的字符串转数字

//Longhand 
var test1 = parseInt('123'); 
var  test2 = parseFloat('12.3'); 
//Shorthand 
var  test1 = +'123'; 
var  test2 = +'12.3';

数组find特定对象(IE不兼容)

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

// 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();

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
}

取下限最佳实践

// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true

字符串重复拼接(IE不兼容)

//longhand 
let test = ''; 
for(let i = 0; i < 5; i ++) {
    
     
  test += 'test '; 
} 
console.log(str); // test test test test test 
//shorthand 
'test '.repeat(5);

查找数组的最大值和最小值

var arr = [1, 2, 3]; 
Math.max(…arr); // 3
Math.min(…arr); // 1

获取字符串某个字符

var str = 'abc';
//Longhand 
str.charAt(2); // c
//Shorthand 
str[2]; // c

校验多个文本框是否为空,输出第一个为空的表单项,语句为xxx不可为空

传统做法

var account = $.trim($('#login-account').val());
            var pwd = $.trim($('#login-pwd').val());
            if (!util.validate(account, "require")) {
    
    
                loginUtil.showError("账号不可为空");
                return;
            }

            if (!util.validate(pwd, "require")) {
    
    
                loginUtil.showError("密码不可为空");
                return;
            }

风骚的逻辑运算符

 var $inputEles = $('input[cn-name]');
            var failtCount = 0;
            for (var i = 0; i < $inputEles.length; i++) {
    
    
                var checkResult = util.validate($($inputEles[i]).val(), 'require');

                //如果校验结果为false 自增校验失败次数 若当前失败次数为0 则说明这逼是第一个校验为空的选项 直接指向逻辑与后面的方法
                checkResult || (failtCount++ == 0 && loginUtil.showError($($inputEles[i]).attr('cn-name') + "不可为空"));
            }

猜你喜欢

转载自blog.csdn.net/shark_chili3007/article/details/119464468