JS 代码片段整理

239 阅读3分钟

两个对象数组的合并去重

let arr1 = [
  { id: 3, city: '上海' },
  { id: 1, city: '北京' },
  { id: 4, city: '成都' },
]
let arr2 = [
  { id: 1, city: '北京' },
  { id: 2, city: '天津' },
  { id: 3, city: '上海' },
  { id: 5, city: '云南' }
]
removeDp(arr1, arr2)
function removeDp (arr1, arr2) {
  let arr = arr1.concat(arr2)
  let obj = {}
  let newArray = arr.reduce((pre, cur) => {
    if (!obj[cur.id]) {
      obj[cur.id] = true
      pre.push(cur)
    }
    return pre
  }, [])
  console.log(newArray)
}

输出结果为

image.png

判断空对象

①、Object.keys(data).length == 0
②、JSON.stringify(data) == "{}"

true + false = 1

说明:布尔值被转换为它们的数字标识

Number(true) // 1
Numnber(false) // 0
1 + 0 = 1

神奇的数字增长

999999999999999; // -> 999999999999999 
9999999999999999; // -> 10000000000000000 

Number.MAX_SAFE_INTEGER 当超过该值,xxx

神奇的数字增长

0.1 + 0.2 不等于 0.3 

为什么呢? 这是由 IEEE 754-2008 双精度浮点数运算误差导致

三个数字比较

1 < 2 < 3; // -> true
3 > 2 > 1; // -> false

说明:

1 < 2 < 3; // 1 < 2 -> true
true < 3; // true -> 1
1 < 3; // -> true

3 > 2 > 1; // 3 > 2 -> true
true > 1; // true -> 1
1 > 1; // -> false

我们可以用 大于或等于运算符(>=

3 > 2 >= 1; // true

把cookie转为键值对

const parseCookie = str =>
  str
    .split(';')
    .map(v => v.split('='))
    .reduce((acc, v) => {
      acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
      return acc;
    }, {});

parseCookie(document.cookie) 
// {_octo: "GH1.1.2059864283.1626332708", tz: "Asia/Shanghai"}

parseCookie('foo=bar; equation=E%3Dmc%5E2');
// { foo: 'bar', equation: 'E=mc^2' }

时间添加天数(返回的是字符串)

const addDaysToDate = (date, n) => {
  const d = new Date(date);
  d.setDate(d.getDate() + n);
  return d.toISOString().split('T')[0];
};
addDaysToDate('2020-10-15', 10); // '2020-10-25'
addDaysToDate('2020-10-15', -10); // '2020-10-05'

返回字符串节数

const byteSize = str => new Blob([str]).size;
byteSize('a') // 1 
byteSize('س') // 2 
byteSize('中') // 3 
byteSize('😀'); // 4 
byteSize('Hello World'); // 11

获取查询字符串参数

URLSearchParams 是接口定义了一些实用的方法来处理 URL 的查询字符串

var paramsString = "q=URLUtils.searchParams&topic=api";

var searchParams = new URLSearchParams(paramsString);

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"

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

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

扁平嵌套的数组

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

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

const immutableObject = {
    name: '肥阳',
    url: 'https://fayyoung.com'
};
Object.freeze(immutableObject);

immutableObject.wechat = 'qq449245884'
immutableObject.name = '王大锤' 
console.log(immutableObject) // {name: "肥阳", url: "https://fayyoung.com"}

使用 Object.seal 创建受控对象

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

const controlledObject = { name: '肥阳' };
Object.seal(controlledObject);
controlledObject.name = '王大锤';
controlledObject.hero = '英雄';
console.log(controlledObject) // {name: "王大锤"}

Arry.from

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);
// ["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" }