const、let、var的区别
const
是常量,定义时必须赋初值,值不可修改。只限制变量绑定的值,不会限制引用数据类型内部的变动。如:
1 2 3 4 5 6 7 8
| const a = 1 a = 2
const b = { name: '张三' } b.name = '李四' b = 1
|
let
声明的是变量。
const
和let
只在块内有效,即两个花括号之间,相当于局部的值。
var
定义的变量是全局的,但一个函数内var
的变量不能在函数外访问。
1 2 3 4 5 6 7 8
| var a = '我是a'
function fun() { console.log(a) var b = '我是b' }
console.log(b)
|
用var
定义两个同名变量,后定义的会覆盖掉先定义的。const
和let
不允许重复定义。
var
存在变量提升的特性。当用var
定义了一个变量,即便还未执行到,该变量也已经存在了,且值为undefined
。
1 2 3 4 5 6
| function fun() { if (a == undefined) { var a = 10 } console.log(a) }
|
造成这种现象的原因是,if
中用var
定义了a
,因变量提升(hoisting)特性,在执行前a
被提升到函数作用域顶部,且初始值为undefined
,于是if
成立,早已存在的a
由undefined
被赋值为10
。
将var
改用let
就不会有这样的问题。
总结:无特殊情况不要用var
,声明变量用let
。声明对象类型用const
,非对象类型用let
。
innerHTML 和 innerText 的区别
1 2 3 4 5 6 7 8 9 10 11 12 13
| <html> <head><title>innerHTML与innerText的区别</title></head> <body> <div id="div1"> <p id="p1">hello world </p> </div> <script> var div1 = document.getElementById("div1"); alert(div1.innerHTML); alert(div1.innerText) </script> </body> </html>
|
正则表达式
各种正则表达式样例
一些常用的正则校验
正则表达式剔除HTML标签与markdown语法符号生成文章简介
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const removeHTML = (htmlStr: string): string => { const scriptRegex: RegExp = new RegExp('<script[^>]*?>[\\s\\S]*?<\\/script>', 'gm')
const styleRegex: RegExp = new RegExp('<style[^>]*?>[\\s\\S]*?<\\/style>', 'gm')
const htmlRegex: RegExp = new RegExp('<[^>]+>', 'gm')
const spaceRegex: RegExp = new RegExp('\\s*|\t|\r|\n', 'gm')
htmlStr = htmlStr.replace(scriptRegex, ""); htmlStr = htmlStr.replace(styleRegex, ""); htmlStr = htmlStr.replace(htmlRegex, ""); htmlStr = htmlStr.replace(spaceRegex, " ");
return htmlStr.trim().substring(0, 100); }
|
剔除<script>
标签可以防止XSS攻击
参观我的个人网站:http://saoke.fun