JavaScript 技巧持续记录

1.转换为数字

一元+运算符

+"42"  // 42
+true  // 1
+false // 0
+null  // 0

其他 Number(value)parseInt()parseFloat

2.管理对象

解构允许我们从对象中提取数据,并将提取的数据分配给变量

const rectangle = { h: 100, w: 200 };
const { h, w } = rectangle;

重命名变量

const { h: height, w: width} = rectangle;
console.log(height); // 100

通过函数对返回的对象进行解构,然后选择要使用的值

function getPerson() {
  return {
    firstName: 'Max',
    lastName: 'Best',
    age: 42
  }
}

const { age } = getPerson();
console.log(age); // 42

通过返回一个对象并选择要返回的片段,从而让一个函数返回多个值

const { age:_ , ...person } = getPerson();
console.log(person); // {firstName: "Max", lastName: "Best"}

3.交换两个变量

let me = 'happy', you = 'sad';
[me, you] = [you, me];
// me = 'sad', you = 'happy

4.设置默认值

变量 :空合并运算符来设置默认值

const bookList = receivedBooks ?? [];

参数 :直接设置默认参数

function calculateArea(width, height = 100) {
    return width * height;
}

const area = calculateArea(50);
console.log(area); // 5000

对象

const rectangle = { height: 400 };
const { height = 750, width = 500 } = rectangle;
console.log(height); // 400 - comes from rectangle object
console.log(width);  // 500 - fallback to default

5.区间随机数

const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

6.删除数组重复项

Set对象类型允许我们存储唯一值。与 … 一起使用

const uniqueArray = [...new Set(array)]

7.动态属性名称

const type = "fruit";
const item = {
  [type]: "kiwi"
};

console.log(item); // {fruit: "kiwi"}

item[type];   // "kiwi"
item["fruit"] // "kiwi"
item.fruit; // "kiwi"

8.不改变原数组,添加新项

const insert = (arr, index, newItem) => [
  ...arr.slice(0, index), // first half of array
  newItem,                // new item
  ...arr.slice(index)     // rest of array
];

const items = ['S', 'L', 'C', 'E']
const result = insert(items, 2, 'I');
console.log(result); // ["S", "L", "I", "C", "E"]

9.箭头函数

如果函数主体是单个表达式,则不需要写范围括号{}和return关键字。
如果函数只有单个参数,则不需要写参数括号()。
如果函数主体表达式是字典(dictionary),那必须将它封闭在括号()内。

箭头函数不定义范围,而是存在于父范围内。这避免了使用this关键字可能会引起的许多陷阱。箭头函数对this没有绑定。在箭头函数内部,this的值与在父范围中的相同。因此,箭头函数不能用作方法或构造函数。箭头函数不适用于apply,bind或call,也没有对super的绑定。

let x = [1, 2, 3, 4]

x.map(val => val * 2)                // [2, 4, 6, 8]
x.filter(val => val % 2 == 0)        // [2, 4]
x.reduce((acc, val) => acc + val, 0) // 10

10.可选链

person && person.name && person.name.first // undefined
person?.name?.first // undefined

11.Nullish合并

在引入Nullish合并运作符之前,JavaScript开发人员使用OR运算符 ||(如果缺少输入)回退到默认值。这伴随着一个重要的警告:即使合法但falsy的值也会导致回退到默认值。

function print(val) {
    return val || 'Missing'
}

print(undefined) // 'Missing'
print(null)      // 'Missing'

print(0)         // 'Missing'
print('')        // 'Missing'
print(false)     // 'Missing'
print(NaN)       // 'Missing'

JavaScript现在提出了空值合并运算符 ??,这为我们提供了一个更好的选择:如果前面的表达式为null-ish,它只会导致回退。这里的null-ish表示null或undefined的值。

function print(val) {
    return val ?? 'Missing'
}

print(undefined) // 'Missing'
print(null)      // 'Missing'

print(0)         // 0
print('')        // ''
print(false)     // false
print(NaN)       // NaN

12.逻辑分配

if (x === null || x == undefined) {
    x = y
}
x ?? (x = y) // x = y if x is nullish, else no effect
x ??= y // x = y if x is nullish, else no effect
x ||= y // x = y if x is falsy, else no effect
x &&= y // x = y if x is truthy, else no effect

13.async和await

JavaScript的强大功能之一就是它的异步性。这意味着许多长时间运行或非常耗时的函数可以返回Promise而不阻塞执行。

const url = 'https://the-one-api.dev/v2/book'
let prom = fetch(url)
prom // Promise {<pending>}

// wait a bit
prom // Promise {<fullfilled>: Response}, if no errors
// or
prom // Promise {<rejected>: Error message}, if any error

调用fetch返回Promise,该Promise在创建时的状态为pending。很快,当API返回响应时,它将转换为fulfilled状态,并包装可以访问的Respond。在Promises世界中,你将执行以下操作来进行API调用并将响应解析为JSON。

const url = 'https://the-one-api.dev/v2/book'
let prom = fetch(url)
prom                               // Promise {<fullfilled>: Response}
  .then(res => res.json())
  .then(json => console.log(json)) // prints response, if no errors
  .catch(err => console.log(err))  // prints error message, if any error

2017年,JavaScript宣布了两个新的关键字async和await,这使Promises的处理和使用变得更加轻松和流畅。它们不是Promises的替代品;它们只是强大的Promises概念之上的语法糖。

取代了将所有代码都发生在一系列then函数内,await让一切看起来像是同步的JavaScript。另外一个好处是,你可以将try … catch与await结合使用,而不是像直接使用Promises那样处理catch函数中的错误。用await表示的相同代码如下所示。

const url = 'https://the-one-api.dev/v2/book'
let res = await fetch(url) // Promise {<fullfilled>: Response} -await-> Response
try {
    let json = await res.json()
    console.log(json) // prints response, if no errors
} catch(err) {
  console.log(err)  // prints error message, if any error
}

async关键字就是硬币的另一面,它包装了将在Promise中发送的所有数据。想一下假设我们要在以下异步函数中添加多个数字。当然,在现实世界中,代码执行的肯定是更为复杂的操作。

async function sum(...nums) {
    return nums.reduce((agg, val) => agg + val, 0)
}

sum(1, 2, 3)                    // Promise {<fulfilled>: 6}
  .then(res => console.log(res) // prints 6

let res = await sum(1, 2, 3)    // Promise {<fulfilled>: 6} -await-> 6
console.log(res)                // prints 6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值