什么是一句话代码

我会收集一些平时遇到的,可以只用一行代码实现的功能

数组操作

生成一个从 0-n 的数组

1
new Set(new Array(n)).map((i, n) => n)

对象操作

用 Reflact方法获取Object的keys,并排序

Reflect 是一个内置的对象,它提供拦截 JavaScript 操作的方法。这些方法与 proxy handlers 的方法相同。Reflect不是一个函数对象,因此它是不可构造的。

Reflect可以配合Proxy使用,作为handles注册get,set

1
2
3
4
5
6
7
const objWithIndices = {
23: 23,
'1': 1,
1000: 1000,
}

Reflect.ownKeys(objWithIndices) // [1,23,1000]

如果不是Number类型的,则按照注册的先后顺序排列

String

JSON.stringify

1
2
3

JSON.stringify({},null,4)

把对象缩进4个空格 配合highlightjs 用来format一长串文本

正则

按照 xxx-xxxx-xxxx 匹配电话号码

如 15000000000,需要变成 150-0000-0000

1
2
3
4

num.replace(/(\d)(?=(\d{4})+\b)/g,'$&-')
// or
num.replace(/(\B)(?=(\d{4})+(?!\d))/g,'-')

具名捕获

1
2
3

new RegExp(/(?<foo>\d+)/g).exec(123).groups.foo // 123

?

匹配 ‘x’ 但是不记住匹配项。这种括号叫作非捕获括号,使得你能够定义与正则表达式运算符一起使用的子表达式。

1
2
3
4


new RegExp(/(?:foo){1,2})/g).exec(foofoo) // foofoo

\1

捕获组,在正则中是 \1 在replace中是$1

1
2
3
4

new RegExp(/(foo) (bar) \1 \2/g).exec(foo bar foo bar) // foo bar foo bar


css

自定义 dashed 样式

1
2
3
4
5
6
7
background: linear-gradient(white, white) padding-box, repeating-linear-gradient(
-45deg,
#ccc 0,
#ccc 0.25em,
white 0,
white 0.75em
);

dom是否包含某个节点

1
2
3

document.body.contains(document.getElementById('id'))
// return true / false

shell

查找文件夹

1
2
3
4
5
6
7

find [PATH] [Option] [action]

## 在根目录查找名字叫foo的文件夹

find / -name FILENAME

server vue-cli build后的index.html

一开始我使用的是http-server,但是因为使用的是history模式,所以页面刷新后就提示404 not found了,后来查阅了github上的issue,有人推荐用serve.可以很好的解决重定向的问题.

1
2
3

serve -s PATH

杂项

文件下载格式

无格式下载文件,需要自行在Content-disposition中添加文件后缀:attachment;filename=aaa.xls

1
2
3
4
5

{
"Content-Type":"application/octet-stream"
}

查询端口进程

1
2
3
4

lsof -i:{端口号}
kill {pid}

Symbol的作用

任何两个Symbol都是不相等的

使用Symbol.fordescription相同 可以创建2个相同的Symbol

Symbol.iterator被称为可迭代对象,可以在for/of循环中使用async方法

Symbol表示对象内部状态,可以很好地隔离用户数据和程序状态。

当form中只有一个input的时候回车会直接提交

在用element ui的时候发现了这个问题

1
2
3
4
5
6
7
8
9
10
11
12

<form action="https://baidu.com">
<label for="input">提交按钮type 不是 submit</label>
<input type="text" id="input">

<label for="input2">多余一个 input</label>
<textarea name="" id="" cols="30" rows="10"></textarea>
<button type="button">只是按钮
</button>
</button>
</form>

git操作

强制推送subtree

1
2
3

git push origin `git subtree push --prefix=dist origin master`:production --force

动态引入模块

利用webpack的解析能力动态引入相应的模块

1
2
3
4
5
6
require.context(
directory,
(useSubdirectories = true),
(regExp = /^\.\/.*$/),
(mode = 'sync')
);

import/export

es2015模块的导入导出