1、去除字符串左右两边的空格(利用正则实现trim)
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>去除字符串左右两边的空格</title>
- </head>
- <body>
- <input type="text" id="content" placeholder="去除字符串左右两边的空格">
- <input type="button" value="去除空格" id="trim">
- <script>
- function getId(obj) {
- return document.getElementById(obj);
- }
- let myTrim = getId('trim'),
- content = getId('content');
- myTrim.onclick = _ => content.value = content.value.replace(/^(s|u00A0)+|(s|u00A0)+1/g,"");
- </script>
- </body>
- </html>
2、区分对象的属性名是对象成员还是原型链继承的
- var obj = {a:1, b:2}
- Object.prototype.add = function(a, b) {
- return a+b
- }
- for(let i in obj) {
- if (obj.hasOwnProperty(i)) {
- console.log('obj的成员:'+i)
- } else {
- console.log('从原型链上继承的:' + i)
- }
- }
在异步请求中,我们很多数据都是 json 格式的,就存在 a.b.c.d 获取 d 的值,如果直接使用 a.b.c.d 可以会出现 a 或者 b 或者 c 对象未获取而报错,为了避免问题的存在可以使用 if 判断,但是多个 if 的判断会让简单的程序变得难以理解,下面我利用 &&(js中串行执行,如 x && y, 只有成功执行了 x 才会执行后面的 y, 当 x 未定义时还能第一时间给出报错,将错误第一时间去除 ) 来简化这个问题
- var a = {b: {c: {d: 1}}}
- if (a) {
- if (a.b) {
- if (a.b.c) {
- if (a.b.c.d) {
- console.log(a.b.c.d)
- }
- }
- }
- }
- // 下面利用 && 优化一下上面的判断
- a && a.b && a.b.c && a.b.c.d && console.log(a.b.c.d)
- 可以将a, b, c, d 任何一个更改一下,就可以看到效果
js 中将不需要的对象(Array,Object等对象类型)释放
对象 = null
js 中将不需要的基本类型 (Number,String,Boolean,Symbol等)释放
基本类型 = undefined
node 跨域处理方法
来源张培跃的 Node.js如何设置允许跨域 下面是我遇到的两种情况
- server.all('*', function (req, res, next) {
// IE 浏览器下访问 (req.headers.origin) 可能出现 undefined , 将设置为允许任意域名跨域
req.headers.origin = (typeof (req.headers.origin) === 'undefined') ? '*' : req.headers.origin
res.header('Access-Control-Allow-Origin', req.headers.origin)
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
next()
}) - server.all('*', function (req, res, next) {
// 页面在 http://localhost:xxx 此时这个 xxx 并非 port 的值(域名相同但端口不同)时,可以访问 => req.headers.origin.toLowerCase() === 'http://localhost'
// 当页面在本地打开即路径可能是 (file:///E:/express/mongodb/1.html) => req.headers.origin.toLowerCase() === 'null'
if (req.headers.origin.toLowerCase() === 'http://localhost' || req.headers.origin.toLowerCase() === 'null') {
res.header('Access-Control-Allow-Origin', req.headers.origin) res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
next()
})