JavaScript不常用但很实用的几个技巧

JavaScript is a widely used web programming language. If you’re getting into software engineering or coding in particular and you want to focus on web development, learning JavaScript is probably the best thing to do.
JavaScript是一种广泛使用的web编程语言。如果你想进入软件工程或编码领域,并且你想专注于web开发,那么学习JavaScript可能是最好的选择。

今天学习到了几个JavaScript不常用但很实用的技巧,分享给大家。

Tip 1 console.table()

console.table()可以将数组或对象以表格的形式在控制台打印出来,让我们可以更加方便直观的看到数据的结构。

const myArr = ['Kolade', 'Chelsea', 10, true];
console.table(myArr)

在这里插入图片描述

const myObj = {
  name: 'Kolade',
  luckyNum: 10,
  lovesFootball: true,
};
console.table(myObj)

在这里插入图片描述

const myObj = {
  name: 'Kolade',
  luckyNum: 10,
  lovesFootball: true,
    firend:{
        name:"Jack",
        luckyNum:8
     }
};
console.table(myObj);
console.log(myObj);

在这里插入图片描述

Tip 2 Template Interpolation

使用模板插值来渲染字符串而不是赋值操作符

const name = 'Tom';
const age = 28;

const plusConcat =
  'Hi there: \n My name is ' + name + ' and I am ' + age + ' years old.';

const templateLiteralConcat = `Hi there: \n My name is, ${name} and I am ${age} years old.`;

Tip 3 Unary Plus

使用一元加号和数字构造函数将字符串转换为数字

const myNum = '5';

convertNum1 = +myNum;
convertNum2 = Number(myNum);

console.log(convertNum1, typeof convertNum1); // 5 'number'
console.log(convertNum2, typeof convertNum2); // 5 'number'

Tip 4 console.group()

console.group('Bio:');

console.log('My name is Kolade');
console.warn("I don't like to be late");
console.error('You came late');

console.groupEnd();

在这里插入图片描述

Tip 5 style for console.log()

const styles = `padding: 15px;
                background-color: #2ecc71;
                color: black`;

console.log('%c Hello, Everyone!', styles);

or

console.log(
  '%c Hello, Everyone!',
  'padding: 15px; background-color: #2ecc71; color: black'
);

在这里插入图片描述

Tip 6 Math Object

let x;

// Get the square root of a number
x = Math.sqrt(9);

// convert a number to absolute value
x = Math.abs(-5); // 5

// Round up a number to the nearest whole number
x = Math.round(4.6);

// Round up a number
x = Math.ceil(4.2); // 5

// Round down a number
x = Math.floor(4.9); // 4

// Exponent of a number
x = Math.pow(2, 3); // 8

// Get the minimum number
x = Math.min(4, 5, 3); // 3

// Get the maximum number
x = Math.max(4, 5, 3); // 5

// Get a random number/decimal between 0 and 1
x = Math.random();

// Get a random number between 1 and 200
x = Math.floor(Math.random() * 200 + 1); // any number between and 200

console.log(x);

Tip 7 First Letter Capitalize

const str = 'john';
const capitalizedStr = (str) => str.charAt(0).toUpperCase() + str.slice(1);

console.log(capitalizedStr(str)); // John
console.log(capitalizedStr('doe')); // Doe

使用charAt(0)获取到首字母,toUpperCase()将其转化为大写字符,在用slice()将其与后面的连接。

Tip 8 Destructure with Default Values

如果使用默认值解构,而在解构期间数组或对象中不存在期望的值,则将使用默认值。这有助于防止错误,并确保代码优雅地处理丢失的数据。
在数组中的使用:

// Destructuring without default values
const fruits = ['Apple', 'Banana'];
const [firstFruit, secondFruit, thirdFruit] = fruits;

console.log(firstFruit); // Apple
console.log(secondFruit); // Banana
console.log(thirdFruit); // undefined

// Destructuring with default values
const [fruit1, fruit2, fruit3 = 'Orange'] = fruits;

console.log(fruit1); // Apple
console.log(fruit2); // Banana
console.log(fruit3); // Orange

在对象中使用:

// Without default values
const person = { name: 'John Doe', age: 30 };
const { name, age, occupation } = person;
console.log(name); // John Doe
console.log(age); // 30
console.log(occupation); // undefined

// With default values
const { firstName = 'John', lastName = 'Doe', gender = 'Male' } = person;
console.log(firstName); // John
console.log(lastName); // Doe
console.log(gender); // Male

Tip 9 The Spread Operator

可以在各种场景中使用扩展操作符,例如复制数组、合并数组、克隆对象以及向函数传递多个参数。
在数组中:

const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];

console.log(copiedArray); // [1, 2, 3]

// merge two or more arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const mergedArray = [...arr1, ...arr2];

console.log(mergedArray); // [1, 2, 3, 4, 5, 6

在对象中:

const originalObj = { name: 'John', age: 30 };
const clonedObj = { ...originalObj };

console.log(clonedObj); // { name: 'John', age: 30 }

在函数中以此传递多个参数

function addNumbers(a, b, c) {
  return a + b + c;
}

const numbers = [10, 12, 8];
const sum = addNumbers(...numbers);

console.log(sum); // 30

Tip 10 Arrow Function

// Traditional Function Expression
function add1(a, b) {
  return a + b;
}

// Arrow Function
const add2 = (a, b) => a + b;

console.log(add1(1, 2)); // 3
console.log(add2(5, 8)); // 13

函数的返回值只有一句的时候,在箭头函数中可以省略花括号和return关键字

// Using Traditional Function Expression
const numbers1 = [3, 4];
const numbers2 = [2, 8];

const squared1 = numbers1.map(function (num) {
  return num * num;
});

// Using Arrow Function
const squared2 = numbers2.map((num) => num * num);

console.log(squared1); // [ 9, 16 ]
console.log(squared2); // [ 4, 64 ]

Tip 10 Remove Duplicates

// create unique arrays with Set()
const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(arrayWithDuplicates)];

console.log(uniqueArray); // [1, 2, 3, 4, 5]

// create unique arrays with Map()
const fruitsWithDuplicates2 = [
  'Mango',
  'Cashew',
  'Barley',
  'Mango',
  'Barley',
  'Berry',
  'Cashew',
];
const uniqueFruitsWithDuplicates2 = [
  ...new Map(fruitsWithDuplicates2.map((item) => [item, true])).keys(),
];

console.log(uniqueFruitsWithDuplicates2);
// [ 'Mango', 'Cashew', 'Barley', 'Berry' ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值