Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS 常用的技巧和几个鲜为人知的特性 #121

Open
husky-dot opened this issue Sep 30, 2019 · 0 comments
Open

JS 常用的技巧和几个鲜为人知的特性 #121

husky-dot opened this issue Sep 30, 2019 · 0 comments

Comments

@husky-dot
Copy link
Owner

作者:Euel Duran

来源: Dev

译者:前端小智


阿里云最近在做活动,低至2折,有兴趣可以看看:
https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=pxuujn3r


JS是一门发展迅速的语言,正因如此,有些新的特性和功能,咱们没有办法在第时间内知道。在这篇文章中,咱们主要探讨一些少有人知道的特性还有一些常用技巧。

获取查询字符串参数

URLSearchParams 是接口定义了一些实用的方法来处理 URL 的查询字符串,它已经存在了好几年了,但它在开发人员中并不流行,有点让人惊讶,咱们来看看如何使用它

var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);

//Iterate the search parameters.
for (let p of searchParams) {
  console.log(p);
}

searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"

使用 Set 对象创建一个惟一的元素列表

用JS创建惟一列表是一项常见的任务,通常通过filtersfor循环来实现,但是还有另一种方法可以利用Set对象来实现这一点。

const list = [1, 2, 3, 5, 2, 5, 7];
const uniqueList = [...new Set(list)];

将原始值数组传递给Set对象,它创建一组惟一值,然后使用展开操作符语法和数组字面量将这些值转回数组。

将原始值列表转换为另一种类型

有时候,后台或 DOM 中处理过的数据不是咱们需要的类型,我在处理数据集的属性时看到过这种情况。假设有以下列表:

const naiveList = ['1500', '1350', '4580'];

想要计算数组中所有元素的和,在JS中,字符串的相加把两个字符串拼接起来,像'1' + '2'它们会连接起来为 ‘12’,通常,要解决这个问题,咱们会使用parseInt函数,但还有另一种方法;咱们可以将数组中的元素转换为所需的基本类型

const castedList = naiveList.map(Number);
console.log(castedList) // [1500, 1350, 4580]

castedList现在包含具有正确Number类型的值。

扁平嵌套的数组

随着单页应用程序体系结构(如Redux)和前端数据规范化等概念的兴起,这种“数据规范化”趋势有时意味着所有元素的 id 都需要放在同一级别。

假设有下面的列表,咱们想扁平它:

const nestedList = [133, 235, 515, [513, 15]];
const flattenList = nestedList.flat();
console.log(flattenList) //  [133, 235, 515, 513, 15]

就像这样,咱们的id数组被扁平了。

使用 object .freeze 避免对象被改变

随着函数式x编程的兴起,数据不可变也越来越重要,咱们可以使用 Object.freeze 来防止对象被更改。

const immutableObject = {
    name: '前端小智',
    url: 'https://小智66.com'
};
Object.freeze(immutableObject);

immutableObject.wechat = 'qq449245884'
immutableObject.name = '王大治' 
console.log(immutableObject) // {name: "前端小智", url: "https://小智66.com"}

使用 Object.seal 创建受控对象

Object.seal() 方法封闭一个对象,阻止添加新属性并将所有现有属性标记为不可配置。当前属性的值只要可写就可以改变,Object.freeze 是啥都不能做,Object.seal() 可以改变属性的值。

const controlledObject = {
    name: '前端小智'
};
Object.seal(controlledObject);
controlledObject.name = '王大冶';
controlledObject.hero = '英雄';  

console.log(controlledObject) // {name: "王大冶"}

确保数组值

使用 grid ,需要重新创建原始数据,并且每行的列长度可能不匹配, 为了确保不匹配行之间的长度相等,可以使用Array.fill方法。

let array = Array(5).fill('');
console.log(array); // outputs (5) ["", "", "", "", ""]

数组 map 的方法 (不使用Array.Map)

另一种数组 map 的实现的方式,不用 Array.map

Array.from 还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。如下:

const cities = [
    { name: 'Paris', visited: 'no' },
    { name: 'Lyon', visited: 'no' },
    { name: 'Marseille', visited: 'yes' },
    { name: 'Rome', visited: 'yes' },
    { name: 'Milan', visited: 'no' },
    { name: 'Palermo', visited: 'yes' },
    { name: 'Genoa', visited: 'yes' },
    { name: 'Berlin', visited: 'no' },
    { name: 'Hamburg', visited: 'yes' },
    { name: 'New York', visited: 'yes' }
];

const cityNames = Array.from(cities, ({ name}) => name);
console.log(cityNames);
// outputs ["Paris", "Lyon", "Marseille", 
// "Rome", "Milan", "Palermo", "Genoa", "Berlin", "Hamburg", "New York"]

有条件的对象属性

不再需要根据一个条件创建两个不同的对象,可以使用展开运算符号来处理。

nst getUser = (emailIncluded) => {
  return {
    name: 'John',
    surname: 'Doe',
    ...emailIncluded && { email : 'john@doe.com' }
  }
}

const user = getUser(true);
console.log(user); // outputs { name: "John", surname: "Doe", email: "john@doe.com" }

const userWithoutEmail = getUser(false);
console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }

动态属性名

早期,如果属性名需要是动态的,我们首先必须声明一个对象,然后分配一个属性。这些日子已经过去了,有了ES6特性,我们可以做到这一点。

const dynamic = 'email';
let user = {
    name: 'John',
    [dynamic]: 'john@doe.com'
}
console.log(user); // outputs { name: "John", email: "john@doe.com" }

代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug

原文: https://dev.to/duranenmanuel/6-things-you-probably-did-not-know-javascript-could-do-natively-2pen

每次整理文章,一般都到2点才睡觉,一周4次左右,挺苦的,还望支持,给点鼓励

交流

阿里云最近在做活动,低至2折,有兴趣可以看看:https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=pxuujn3r

干货系列文章汇总如下,觉得不错点个Star,欢迎 加群 互相学习。

https://github.com/qq449245884/xiaozhi

因为篇幅的限制,今天的分享只到这里。如果大家想了解更多的内容的话,可以去扫一扫每篇文章最下面的二维码,然后关注咱们的微信公众号,了解更多的资讯和有价值的内容。

clipboard.png

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant