天天看点

33个有用的JavaScript 秘籍

33个有用的JavaScript 秘籍

英文 | https://javascript.plainenglish.io/33-javascript-useful-shorthands-cheat-list-2021-e08b46a1a688

翻译 | 杨小二

作为开发人员,我体验到学习是一个持续的过程。随着每年都有新技术的出现与技术升级,我们都需要相应地进行技术更新,并且在工作和项目中进行充分利用它。

今天,我想与你分享一些我自己常用的JavaScript的技巧,它对我的工作提供了很大的帮助,同时,这些技巧会让代码更具有可读性。

那么,就让我们开始今天的内容吧。

1、if

你是否对使用大量 if 语句感到厌烦?让我们检查一些可以在这里提供帮助的选项。

//longhand
if (fruit === 'apple' || fruit === 'banana' || fruit === 'orange' || fruit ==='mango') {
    //logic
}
//shorthand
if (['apple', 'banana', 'orange', 'mango'].includes(fruit)) {
   //logic
}      

2、 If... else 简写

当我们想使用 if-else 语句时,这个会对你有所帮助。当你使用 2-3 个 if.. else 时,它会降低你代码的可读性。

// Longhand
let mychoice: boolean;
if (money > 100) {
    mychoice= true;
} else {
    mychoice= false;
}
// Shorthand
let mychoice= (money > 10) ? true : false;
//or we can use directly
let mychoice= money > 10;
console.log(mychoice);      

嵌套条件如下所示:

let salary = 300,
checking = (salary > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(checking); // "greater than 100"      

3、变量声明

当我们有相同类型的变量时,我们可以避免写入两次。

//Longhand 
let data1;
let data2= 1;
//Shorthand 
let data1, data2= 1;      

4、检查非空值

如果我们想检查变量不为空怎么办?我们现在可以摆脱再次写入所有条件。

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

5、分配默认值

let data1 = null,
    data2 = test1 || '';
console.log("null check", data2); // output will be ""      

6、未定义值检查

let data1 = undefined,
    data2 = data1 || '';
console.log("undefined check", data2); // output will be ""      

正常值检查

let data1 = 'data',
    data2 = data1 || '';
console.log(data); // output: 'data'      

(注意:我们也可以对主题 4,5 和 6使用运算符??)

7、空运算符

如果左侧为空或未定义,则此运算符返回右侧值。

const data= null ?? 'data';
console.log(data);
// expected output: "data"
const data1 = 1 ?? 4;
console.log(data1);
// expected output: 1      

8、赋值

//Longhand 
let data1, data2, data3;
data1 = 1;
data2 = 2;
data3 = 3;
//Shorthand 
let [data1, data2, data3] = [1, 2, 3];      

9、赋值运算符

它主要在我们处理算术运算符时使用,就个人而言,我喜欢这里的简写,因为它更具可读性。

// Longhand
data1 = data1 + 1;
data2 = data2 - 1;
data3 = data3 * 30;
// Shorthand
data1++;
data2--;
data3 *= 30;      

10、空检查

最常用的操作数之一,但请确保你的值为真、非空字符串、定义的值和非空值。

// Longhand
if (data1 === true) or if (data1 !== "") or if (data1 !== null)
// Shorthand //
if (test1)      

注意:如果 test1 有任何值,它将落入 if 循环之后的逻辑中,该运算符主要用于 null 或 undefined 检查。

11、 AND(&&) 运算符

如果我们想避免少使用一个 if 语句,那么这个技巧会很有帮助。

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

12、返回简写

这将有助于避免使用大量代码,专门返回到基于返回语句的调用方法。

// Longhand
let value;
function returnMe() {
    if (!(value === undefined)) {
        return value;
    } else {
        return callFunction('value');
    }
}
var data = returnMe();
console.log(data); //output value
function callFunction(val) {
    console.log(val);
}


// Shorthand
function returnMe() {
    return value || callFunction('value');
}      

13、 箭头函数

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

让我们再看一个例子。

function function(value) {
  console.log('value', value);
}
function= value => console.log('value', value);      

14、短函数调用

我们可以使用三元运算符来实现这些功能。

// Longhand
function data1() {
    console.log('data1');
};
function data2() {
    console.log('data2');
};
var data3 = 1;
if (data3 == 1) {
    data1();
} else {
    data2();
} //data1
// Shorthand
(data3 === 1 ? data1 : data2)(); //data1      

15、Switch语句优化

如果你想优化你的 switch 语句,那么这个可以提供帮助。

// Longhand
switch (data) {
    case 1:
        data1();
        break;
    case 2:
        data2();
        break;
    case 3:
        data();
        break;
        // And so on...
}
// Shorthand
var data = {
    1: data1,
    2: data2,
    3: data
};
const val = 1
data[val]();
function data1() {
    console.log("data1");
}
function data2() {
    console.log("data2");
}
function data() {
    console.log("data");
}      

16、 隐式回报

即使不编写 return 语句,箭头函数也可以帮助返回值,酷吧?

//longhand
function calculate(diameter) {
  return Math.PI * diameter
}
//shorthand
calculate = diameter => (
  Math.PI * diameter;
)      

17、十进制指数

// Longhand
for (var i = 0; i < 100000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e5; i++) {      

18、默认参数值

//Longhand
function add(data1, data2) {
    if (data1 === undefined) data1 = 1;
    if (data2 === undefined) data2 = 2;
    return data1 + data2;
}
//shorthand
add = (data1 = 1, data2 = 2) => data1 + data2;
console.log(add()); //output: 3      

19、 传播运算符

在另一个地方创建数组引用和浅拷贝也很有用。

//longhand
// joining arrays using concat
const testdata= [1, 2, 3];
const values = [4 ,5 , 6].concat(data);
//shorthand
// joining arrays
const testdata = [1, 2, 3];
const values = [4 ,5 , 6, ...testdata];
console.log(test); // [ 4, 5, 6, 1, 2, 3]      

对于克隆,我们也可以使用扩展运算符。

//longhand
// cloning arrays
const data1 = [1, 2, 3];
const data2 = data1.slice()
//shorthand
// cloning arrays
const data1 = [1, 2, 3];
const data2 = [...data1];      

20、模板文字

如果你正在寻找以在字符串中附加多个值的技巧的话,那么此技巧适合你。

//longhand
const literal = 'Hi ' + data1 + ' ' + data2 + '.'
//shorthand
const literal= `Hi ${data1} ${data2}`;      

21、多行字符串

//longhand
const literal = 'abc abc abc abc abc abc\n\t'
    + 'val test,test test test test\n\t'
//shorthand
const literal = `abc abc abc abc abc abc
         val test,test test test test`      

22、对象属性赋值

let data1 = 'abcd'; 
let data2 = 'efgh';
//Longhand 
let data = {data1: data1, data2: data2}; 
//Shorthand 
let data = {data1, data2};      

23、数字转换

//Longhand 
let test1 = parseInt('12'); 
let test2 = parseFloat('2.33');
//Shorthand 
let test1 = +'12'; 
let test2 = +'2.33';      

24、解构赋值

//longhand
const data1 = this.data.data1;
const data2 = this.data.data2;
const data2 = this.data.data3;
//shorthand
const { data1, data2, data3 } = this.data;      

25、 Array.find 方法

从数组中找到第一个匹配值的方法之一。

const data = [{
        type: 'data1',
        name: 'abc'
    },
    {
        type: 'data2',
        name: 'cde'
    },
    {
        type: 'data1',
        name: 'fgh'
    },
]
function datafinddata(name) {
    for (let i = 0; i < data.length; ++i) {
        if (data[i].type === 'data1' && data[i].name === name) {
            return data[i];
        }
    }
}
//Shorthand
filteredData = data.find(data => data.type === 'data1' && data.name === 'fgh');
console.log(filteredData); // { type: 'data1', name: 'fgh' }      

26、按位索引

如果我们可以将 indexof 方法与速记结合起来会怎样?按位 indexof 方法为我们做同样的工作。

//longhand
if (data.indexOf(item) > -1) { // item found
}
if (data.indexOf(item) === -1) { // item not found
}
//shorthand
if (~data.indexOf(item)) { // item found
}
if (!~data.indexOf(item)) { // item not found
}      

我们也可以使用包含功能。

if (data.includes(item)) { 
// true if the item found
}      

27、 Object.entries()

此功能有助于将对象转换为对象数组。

const data = {
    data1: 'abc',
    data2: 'cde',
    data3: 'efg'
};
const arr = Object.entries(data);
console.log(arr);
//[
    ['data1', 'abc'],
    ['data2', 'cde'],
    ['data3', 'efg']
]      

28、Object.values() 和 Object.keys()

迭代对象值会很有帮助。

const data = {
    data1: 'abc',
    data2: 'cde'
};
const arr = Object.values(data);
console.log(arr);
//[ 'abc', 'cde']      

Object.keys() 有助于迭代对象中的键。

const data = {
    data1: 'abc',
    data2: 'cde'
};
const arr = Object.keys(data);
console.log(arr);
//[ 'data1', 'data2']      

29、 双位速记

(双非按位运算符方法仅适用于 32 位整数)

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

30、多次重复一个字符串

此字符串方法有助于一次又一次地重复相同的字符串值。

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

31、查找数组中的最大值和最小值

const data = [1, 4, 3]; 
Math.max(…data); // 4
Math.min(…data); // 1      

32、从字符串中获取字符

let str = 'test';
//Longhand 
str.charAt(2); // s
//Shorthand 
Note: this is only works if we know the index of matched character
str[2]; // c      

33、Power 简写

//longhand
Math.pow(2,2); // 4
//shorthand
2**2 // 4      

本文完~

学习更多技能

请点击下方公众号