常用的JavaScript技巧

// 1.声明变量
// Longhand
let x;
let y = 20;
//Shorthand
let x, y = 20;

// 2.给多个变量赋值
// (使用数组解构来在一行中给多个变量赋值。)
// Longhand
let a, b, c;
a = 5;
b = 6;
c = 12;
// Shorthand
let [a, b, c] = [5, 6, 12]

// 3.三元运算符
// Longhand
let marks = 26;
let result;
if (marks >= 30) {
    
    
  result = 'Pass';
} else {
    
    
  result = 'Fail'
}
// Shorthand
let result = marks >= 30 ? 'Pass' : 'Fail'

// 4.赋默认值
// Longhand
let imagePath;
let path = getImagePath();
if (path !== null && path !== undefined && path !== '') {
    
    
  imagePath = path;
} else {
    
    
  imagePath = 'logo.jpg'
}
// Shorthand
let imagePath = getImagePath() || 'logo.jpg'

// 5. 与 (&&) 短路运算
//Longhand
if (isLoggedin) {
    
    
  goToHomepage();
}
//Shorthand
isLoggedin && goToHomepage();

// 6.交换两个变量
let x = 'hello', y = 20;
// Longhand
const temp = x;
x = y;
y = temp;
// Shorthand
[x, y] = [y, x];

// 7.箭头函数
// Longhand
function add (num1, num2) {
    
    
  return num1 + num2;
}
// Shorthand
const add = (num1, num2) => num1 + num2;

// 8.模板字符串
// Longhand
console.log('You got a missed call from ' + number + ' at ' + time);
// Shorthand
console.log(`You got a missed call from ${
      
      number} at ${
      
      time}`);

// 9. 多行字符串
//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.`);

// 10. 多条件检查
//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
}

// 11.对象属性复制
let firstname = 'Amitav';
let lastname = 'Mishra';
// Longhand
let obj = {
    
    firstname: firstname, lastname: lastname};
// Shorthand
let obj = {
    
    firstname, lastname};

// 12.字符串传成数字
// Longhand
let total = parseInt('453');
let average = parseFloat('42.6');
// Shorthand
let total = +'453';
let average = +'42.6';

// 13.重复一个字符串多次
// Longhand
let str = '';
for(let i = 0; i < 5; i ++) {
    
    
  str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello
// Shorthand
'Hello '.repeat(5);

// 14.指数幂
// Longhand
const power = Math.pow(4, 3); // 64
// Shorthand
const power = 4**3; // 64

// 15. 双非位运算符 (~~)
// 双非位运算符只对 32 位整数有效,例如 (2**31)-1 = 2147483647。所以对于任何大于 2147483647 的数字,双非位运算符 (~~) 都会给出错误的结果,这种情况下推荐使用 Math.floor() 方法。
// Longhand
const floor = Math.floor(6.8); // 6
// Shorthand
const floor = ~~6.8; // 6

// 16.数组中的最大和最小数字
// Shorthand
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2

// 17.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]);
}

// for...in循环来遍历对象属性。
let obj = {
    
    x: 20, y: 50};
for (const key in obj) {
    
    
  console.log(obj[key]);
}

// 18. 合并数组
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]


// 19.获取字符串中的字符
let str = 'jscurious.com';
//Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c

// 20.Replace All
var example = "potato potato";
console.log(example.replace(/pot/, "tom"));
// "tomato potato"
console.log(example.replace(/pot/g, "tom"));
// "tomato tomato"

// 21.提取唯一值
var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8]

// 22.将数字转换为字符串
var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string

// 23.将字符串转换为数字
// 请注意这里的用法,因为它只适用于“字符串数字”。
the_string = "123";
console.log(+the_string);
// 123
the_string = "hello";
console.log(+the_string);
// NaN

// 24.随机排列数组中的元素
var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(my_list.sort(function() {
    
    
  return Math.random() - 0.5
}));
// [4, 8, 2, 9, 1, 3, 6, 5, 7]

// 25.展平二维数组
var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9]

// 26.动态属性名称
const dynamic = 'flavour';
var item = {
    
    
  name: 'Coke',
  [dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" }

// 27.使用 length 调整大小 / 清空数组
// 调整数组的大小:
var entries = [1, 2, 3, 4, 5, 6, 7];
console.log(entries.length);
// 7
entries.length = 4;
console.log(entries.length);
// 4
console.log(entries);
// [1, 2, 3, 4]

// 清空数组:
var entries = [1, 2, 3, 4, 5, 6, 7];
console.log(entries.length);
// 7
entries.length = 0;
console.log(entries.length);
// 0
console.log(entries);
// []

猜你喜欢

转载自blog.csdn.net/AnnyXSX/article/details/112867912