64个JS技巧

143 阅读10分钟

1. 声明和初始化数组

我们可以使用默认值(如""、null或 )初始化特定大小的数组0。您可能已经将这些用于一维数组,但如何初始化二维数组/矩阵呢?

const array = Array(5).fill(''); 
// 输出
(5) ["", "", "", "", ""]

const matrix = Array(5).fill(0).map(()=>Array(5).fill(0)); 
// 输出
(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]
length: 5
复制代码

2. 找出总和、最小值和最大值

我们应该利用reduce方法来快速找到基本的数学运算。

const array  = [5,4,7,8,9,2];
复制代码
array.reduce((a,b) => a+b);
// 输出: 35
复制代码
  • 最大限度
array.reduce((a,b) => a>b?a:b);
// 输出: 9
复制代码
  • 最小
array.reduce((a,b) => a<b?a:b);
// 输出: 2
复制代码

3. 对字符串、数字或对象数组进行排序

我们有内置的方法sort()reverse()用于对字符串进行排序,但是数字或对象数组呢?

让我们看看数字和对象的升序和降序排序技巧。

  • 排序字符串数组
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// 输出
(4) ["Joe", "Kapil", "Musk", "Steve"]

stringArr.reverse();
// 输出
(4) ["Steve", "Musk", "Kapil", "Joe"]
复制代码
  • 排序数字数组
const array  = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// 输出
(6) [1, 5, 10, 25, 40, 100]

array.sort((a,b) => b-a);
// 输出
(6) [100, 40, 25, 10, 5, 1]
复制代码
  • 对象数组排序
const objectArr = [     { first_name: 'Lazslo', last_name: 'Jamf'     },    { first_name: 'Pig',    last_name: 'Bodine'   },    { first_name: 'Pirate', last_name: 'Prentice' }];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// 输出
(3) [{…}, {…}, {…}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3
复制代码

4. 从数组中过滤出虚假值

Falsy值喜欢0undefinednullfalse""''可以很容易地通过以下方法省略

const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);
// 输出
(3) [3, 6, 7]
复制代码

5. 对各种条件使用逻辑运算符

如果你想减少嵌套 if…else 或 switch case,你可以简单地使用基本的逻辑运算符AND/OR

function doSomething(arg1){ 
    arg1 = arg1 || 10; 
// 如果尚未设置,则将 arg1 设置为 10 作为默认值
return arg1;
}

let foo = 10;  
foo === 10 && doSomething(); 
// is the same thing as if (foo == 10) then doSomething();
// 输出: 10

foo === 5 || doSomething();
// is the same thing as if (foo != 5) then doSomething();
// 输出: 10
复制代码

6. 删除重复值

您可能已经将 indexOf() 与 for 循环一起使用,该循环返回第一个找到的索引或较新的 includes() 从数组中返回布尔值 true/false 以找出/删除重复项。 这是我们有两种更快的方法。

const array  = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// 输出: [5, 4, 7, 8, 9, 2]
复制代码

7. 创建计数器对象或映射

大多数情况下,需要通过创建计数器对象或映射来解决问题,该对象或映射将变量作为键进行跟踪,并将其频率/出现次数作为值进行跟踪。

let string = 'kapilalipak';

const table={}; 
for(let char of string) {
  table[char]=table[char]+1 || 1;
}
// 输出
{k: 2, a: 3, p: 2, i: 2, l: 2}
复制代码

const countMap = new Map();
  for (let i = 0; i < string.length; i++) {
    if (countMap.has(string[i])) {
      countMap.set(string[i], countMap.get(string[i]) + 1);
    } else {
      countMap.set(string[i], 1);
    }
  }
// 输出
Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}
复制代码

8. 三元运算符很酷

您可以避免使用三元运算符嵌套条件 if…elseif…elseif。

function Fever(temp) {
    return temp > 97 ? 'Visit Doctor!'
      : temp < 97 ? 'Go Out and Play!!'
      : temp === 97 ? 'Take Some Rest!';
}

// 输出
Fever(97): "Take Some Rest!" 
Fever(100): "Visit Doctor!"
复制代码

9. 与旧版相比,for 循环更快

  • forfor..in默认为您提供索引,但您可以使用 arr[index]。
  • for..in 也接受非数字,所以避免它。
  • forEach,for...of直接获取元素。
  • forEach也可以为您提供索引,但for...of不能。
  • forfor...of考虑阵列中的孔,但其他 2 个不考虑。

10.合并2个对象

通常我们需要在日常任务中合并多个对象。

const user = { 
 name: 'Kapil Raghuwanshi', 
 gender: 'Male' 
 };
const college = { 
 primary: 'Mani Primary School', 
 secondary: 'Lass Secondary School' 
 };
const skills = { 
 programming: 'Extreme', 
 swimming: 'Average', 
 sleeping: 'Pro' 
 };

const summary = {...user, ...college, ...skills};

// 输出
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary School"
programming: "Extreme"
secondary: "Lass Secondary School"
sleeping: "Pro"
swimming: "Average"
复制代码

11. 箭头函数

箭头函数表达式是传统函数表达式的紧凑替代品,但有局限性,不能在所有情况下使用。由于它们具有词法范围(父范围)并且没有自己的范围thisarguments因此它们指的是定义它们的环境。

const person = {
name: 'Kapil',
sayName() {
    return this.name;
    }
}
person.sayName();
// 输出
"Kapil"
复制代码

const person = {
name: 'Kapil',
sayName : () => {
    return this.name;
    }
}
person.sayName();
// 输出
""
复制代码

12. 可选链

可选的链接 ?.如果值在 ? 之前,则停止评估。为 undefined 或 null 并返回

undefinedconst user = {
  employee: {
    name: "Kapil"
  }
};
user.employee?.name;
// 输出: "Kapil"
user.employ?.name;
// 输出: undefined
user.employ.name
// 输出: VM21616:1 Uncaught TypeError: Cannot read property 'name' of undefined
复制代码

13. 打乱数组

利用内置Math.random()方法。

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
    return Math.random() - 0.5;
});
// 输出
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]
复制代码

14. 空合并算子

空合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为空或未定义时返回其右侧操作数,否则返回其左侧操作数。

const foo = null ?? 'my school';
// 输出: "my school"

const baz = 0 ?? 42;
// 输出: 0
复制代码

15. Rest & Spread 运算符

那些神秘的3点...可以休息或传播!🤓

function myFun(a,  b, ...manyMoreArgs) {
   return arguments.length;
}
myFun("one", "two", "three", "four", "five", "six");

// 输出: 6
复制代码

const parts = ['shoulders', 'knees']; 
const lyrics = ['head', ...parts, 'and', 'toes']; 

lyrics;
// 输出: 
(5) ["head", "shoulders", "knees", "and", "toes"]
复制代码

16. 默认参数

const search = (arr, low=0,high=arr.length-1) => {
    return high;
}
search([1,2,3,4,5]);

// 输出: 4
复制代码

17. 将十进制转换为二进制或十六进制

在解决问题的同时,我们可以使用一些内置的方法,例如.toPrecision().toFixed()来实现许多帮助功能。

const num = 10;

num.toString(2);
// 输出: "1010"
num.toString(16);
// 输出: "a"
num.toString(8);
// 输出: "12"
复制代码

18. 使用解构简单交换两值

let a = 5;
let b = 8;
[a,b] = [b,a]

[a,b]
// 输出
(2) [8, 5]
复制代码

19. 单行回文检查

嗯,这不是一个整体的速记技巧,但它会让你清楚地了解如何使用弦乐。

function checkPalindrome(str) {
  return str == str.split('').reverse().join('');
}
checkPalindrome('naman');
// 输出: true
复制代码

20.将Object属性转成属性数组

使用Object.entries(),Object.keys()和Object.values()
const obj = { a: 1, b: 2, c: 3 };

Object.entries(obj);
// 输出
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3

Object.keys(obj);
(3) ["a", "b", "c"]

Object.values(obj);
(3) [1, 2, 3]

21.生成指定范围的数字

在某些情况下,我们会创建一个处在两个数之间的数组。假设我们要判断某人的生日是否在某个范围的年份内,那么下面是实现它的一个很简单的方法 😎

let start = 1900, end = 2000;
[...new Array(end + 1).keys()].slice(start);
// [ 1900, 1901, ..., 2000]

// 还有这种方式,但对于很的范围就不太稳定
Array.from({ length: end - start + 1 }, (_, i) => start + i);
复制代码

22.使用值数组作为函数的参数

在某些情况下,我们需要将值收集到数组中,然后将其作为函数的参数传递。 使用 ES6,可以使用扩展运算符(...)并从[arg1, arg2] > (arg1, arg2)中提取数组:

const parts = {
  first: [0, 2],
  second: [1, 3],
}

["Hello", "World", "JS", "Tricks"].slice(...parts.second)
// ["World", "JS"]

复制代码

23.将值用作 Math 方法的参数

当我们需要在数组中使用Math.maxMath.min来找到最大或者最小值时,我们可以像下面这样进行操作:

const elementsHeight =  [...document.body.children].map(
  el => el.getBoundingClientRect().y
);
Math.max(...elementsHeight);
// 474

const numbers = [100, 100, -1000, 2000, -3000, 40000];
Math.min(...numbers);
// -3000
复制代码

24.合并/展平数组中的数组

Array 有一个很好的方法,称为Array.flat,它是需要一个depth参数,表示数组嵌套的深度,默认值为1。 但是,如果我们不知道深度怎么办,则需要将其全部展平,只需将Infinity作为参数即可 😎

const arrays = [[10], 50, [100, [2000, 3000, [40000]]]]

arrays.flat(Infinity)
// [ 10, 50, 100, 2000, 3000, 40000 ]
复制代码

25. 防止代码崩溃

在代码中出现不可预测的行为是不好的,但是如果你有这种行为,你需要处理它。

例如,常见错误TypeError,试获取undefined/null等属性,就会报这个错误。

const found = [{ name: "Alex" }].find(i => i.name === 'Jim')

console.log(found.name)
// TypeError: Cannot read property 'name' of undefined
复制代码

我们可以这样避免它:

const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {}

console.log(found.name)
// undefined
复制代码

26. 传递参数的好方法

对于这个方法,一个很好的用例就是styled-components,在ES6中,我们可以将模板字符中作为函数的参数传递而无需使用方括号。 如果要实现格式化/转换文本的功能,这是一个很好的技巧:

const makeList = (raw) =>
  raw
    .join()
    .trim()
    .split("\n")
    .map((s, i) => `${i + 1}. ${s}`)
    .join("\n");

makeList`
Hello, World
Hello, World
`;
// 1. Hello,World
// 2. World,World
复制代码

27.交换变量

使用解构赋值语法,我们可以轻松地交换变量 使用解构赋值语法 😬:

let a = "hello"
let b = "world"

// 错误的方式
a = b
b = a
// { a: 'world', b: 'world' }

// 正确的做法
[a, b] = [b, a]
// { a: 'world', b: 'hello' }
复制代码

28.按字母顺序排序

需要在跨国际的项目中,对于按字典排序,一些比较特殊的语言可能会出现问题,如下所示 😨

// 错误的做法
["a", "z", "ä"].sort((a, b) => a - b);
// ['a', 'z', 'ä']

// 正确的做法
["a", "z", "ä"].sort((a, b) => a.localeCompare(b));
// [ 'a', 'ä', 'z' ]
复制代码

localeCompare() :用本地特定的顺序来比较两个字符串。

29.隐藏隐私

最后一个技巧是屏蔽字符串,当你需要屏蔽任何变量时(不是密码),下面这种做法可以快速帮你做到:

const password = "hackme";
password.substr(-3).padStart(password.length, "*");
// ***kme
复制代码

30. if多条件判断

// 冗余
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {}

// 简洁
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {}
复制代码

31. if...else...

// 冗余
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}

// 简洁
let test = x > 10;
复制代码

32. Null, Undefined, 空值检查

// 冗余
if (first !== null || first !== undefined || first !== '') {
    let second = first;
}

// 简洁
let second = first || '';
复制代码

33. foreach循环

// 冗余
for (var i = 0; i < testData.length; i++)
    
// 简洁
for (let i in testData)
// 或
for (let i of testData)
复制代码

34. 函数条件调用

// 冗余
function test1() {
  console.log('test1');
};
function test2() {
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}

// 简单
(test3 === 1? test1:test2)();
复制代码

35. switch条件

// 冗余
switch (data) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // so on...
}

// 简洁
var data = {
  1: test1,
  2: test2,
  3: test
};

data[anything] && data[anything]();
复制代码

36. 多行字符串

// 冗余
const data = 'abc abc abc abc abc abc\n\t'
    + 'test test,test test test test\n\t'

// 简洁
const data = `abc abc abc abc abc abc
         test test,test test test test`
复制代码

37. 隐式返回

// 冗余
function getArea(diameter) {
  return Math.PI * diameter
}

// 简洁
getArea = diameter => (
  Math.PI * diameter;
)
复制代码

38. 重复字符串多次

// 冗余
let test = ''; 
for(let i = 0; i < 5; i ++) { 
  test += 'test '; 
} 

// 简洁
'test '.repeat(5);
复制代码

39. 幂乘

// 冗余
Math.pow(2,3);

// 简洁而
2**3 // 8

40. 当同时声明多个变量时,可简写成一行

//Longhand
let x;
let y = 20;
 
//Shorthand
let x, y = 20;
复制代码

41. 利用解构,可为多个变量同时赋值

//Longhand
let a, b, c;

a = 5;
b = 8;
c = 12;

//Shorthand
let [a, b, c] = [5, 8, 12];
复制代码

42. 巧用三元运算符简化if else

//Longhand 
let marks = 26; 
let result; 
if (marks >= 30) {
   result = 'Pass'; 
} else { 
   result = 'Fail'; 
} 

//Shorthand 
let result = marks >= 30 ? 'Pass' : 'Fail';
复制代码

43. 使用||运算符给变量指定默认值

本质是利用了||运算符的特点,当前面的表达式的结果转成布尔值为false时,则值为后面表达式的结果

//Longhand
let imagePath;

let path = getImagePath();

if (path !== null && path !== undefined && path !== '') {
    imagePath = path;
} else {
    imagePath = 'default.jpg';
}

//Shorthand
let imagePath = getImagePath() || 'default.jpg';
复制代码

44. 使用&&运算符简化if语句

例如某个函数在某个条件为真时才调用,可简写

//Longhand
if (isLoggedin) {
    goToHomepage();
 }

//Shorthand
isLoggedin && goToHomepage();
复制代码

45. 使用解构交换两个变量的值

let x = 'Hello', y = 55;

//Longhand
const temp = x;
x = y;
y = temp;

//Shorthand
[x, y] = [y, x];
复制代码

46. 适用箭头函数简化函数

//Longhand
function add(num1, num2) {
  return num1 + num2;
}

//Shorthand
const add = (num1, num2) => num1 + num2;
复制代码

需要注意箭头函数和普通函数的区别

47. 使用字符串模板简化代码

//Longhand
console.log('You got a missed call from ' + number + ' at ' + time);

//Shorthand
console.log(`You got a missed call from ${number} at ${time}`);
复制代码

48. 多行字符串也可使用字符串模板简化

//Longhand
console.log('JavaScript, often abbreviated as JS, is a\n' + 
            'programming language that conforms to the \n' + 
            'ECMAScript specification. JavaScript is high-level,\n' + 
            'often just-in-time compiled, and multi-paradigm.'
            );


//Shorthand
console.log(`JavaScript, often abbreviated as JS, is a
            programming language that conforms to the
            ECMAScript specification. JavaScript is high-level,
            often just-in-time compiled, and multi-paradigm.`
            );
复制代码

49. 对于多值匹配,可将所有值放在数组中,通过数组方法来简写

//Longhand
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
  // Execute some code
}

// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
   // Execute some code
}

// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) { 
    // Execute some code 
}
复制代码

50. 巧用ES6对象的简洁语法

例如,当属性名和变量名相同时,可直接缩写为一个

let firstname = 'Amitav';
let lastname = 'Mishra';

//Longhand
let obj = {firstname: firstname, lastname: lastname};

//Shorthand
let obj = {firstname, lastname};
复制代码

51. 使用一元运算符简化字符串转数字

//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');

//Shorthand
let total = +'453';
let average = +'42.6';
复制代码

52. 使用repeat()方法简化重复一个字符串

//Longhand
let str = '';
for(let i = 0; i < 5; i ++) {
  str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello

// Shorthand
'Hello '.repeat(5);

// 想跟你说100声抱歉!
'sorry\n'.repeat(100);
复制代码

53. 使用双星号代替Math.pow()

//Longhand
const power = Math.pow(4, 3); // 64

// Shorthand
const power = 4**3; // 64
复制代码

54. 使用双波浪线运算符(~~)代替Math.floor()

//Longhand
const floor = Math.floor(6.8); // 6

// Shorthand
const floor = ~~6.8; // 6
复制代码

需要注意,~~仅适用于小于2147483647的数字

55. 简化数组合并

let arr1 = [20, 30];

//Longhand
let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80]

//Shorthand
let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]
复制代码

56. 单层对象的拷贝

let obj = {x: 20, y: {z: 30}};

//Longhand
const makeDeepClone = (obj) => {
  let newObject = {};
  Object.keys(obj).map(key => {
      if(typeof obj[key] === 'object'){
          newObject[key] = makeDeepClone(obj[key]);
      } else {
          newObject[key] = obj[key];
      }
});

return newObject;
}

const cloneObj = makeDeepClone(obj);



//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));

//Shorthand for single level object
let obj = {x: 20, y: 'hello'};
const cloneObj = {...obj};
复制代码

57. 寻找数组中的最大和最小值

// Shorthand
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2
复制代码

58. 使用for in和for of来简化普通for循环

let arr = [10, 20, 30, 40];

//Longhand
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

//Shorthand
//for of loop
for (const val of arr) {
  console.log(val);
}

//for in loop
for (const index in arr) {
  console.log(arr[index]);
}
复制代码

59. 简化获取字符串中的某个字符

let str = 'jscurious.com';

//Longhand
str.charAt(2); // c

//Shorthand
str[2]; // c
复制代码

60. 移除对象属性

let obj = {x: 45, y: 72, z: 68, p: 98};

// Longhand
delete obj.x;
delete obj.p;
console.log(obj); // {y: 72, z: 68}

// Shorthand
let {x, p, ...newObj} = obj;
console.log(newObj); // {y: 72, z: 68}
复制代码

61. 使用arr.filter(Boolean)过滤掉数组成员的值falsey

let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];

//Longhand
let filterArray = arr.filter(function(value) {
    if(value) return value;
});
// filterArray = [12, "xyz", -25, 0.5]

// Shorthand
let filterArray = arr.filter(Boolean);
// filterArray = [12, "xyz", -25, 0.5]

62. 数组对象解构

我们经常使用 ES6 的解构,对于一个数组,每项都是一个对象,如果想获得数组第一项的对象的某个值,可以这样写;

const people = [
  {
    name: "Lisa",
    age: 20,
  },
  {
    name: "Pete",
    age: 22,
  },
  {
    name: "Caroline",
    age: 60,
  }
];

const [{age}] = people;

console.log(age);

// 20

63. 箭头函数直接返回对象

使用箭头函数返回一个对象,为了和函数的 { 区分开来,在外层包一层 ( 即可解决;

const createPerson = (age, name, nationality) => ({
  age,
  name,
  nationality,
});

const caroline = createPerson(27, 'Caroline', 'US');

console.log(caroline);

// {
//   age: 27,
//   name: 'Caroline'
//   nationality: 'US',
// }
复制代码

64. await 链条

我们可以用 filter 和 map 方法接在 await 方法后形成链条过滤或映射处理获取的数据;

const chainDirectly = (await fetch('https://www.people.com'))
  .filter(person => age > 20)
  .filter(person => nationality === 'NL')
复制代码