判断数据类型
1.typeof (返回值字符串)
console.log(typeof true)//boolean
console.log(typeof '')//string
console.log(typeof 1)//number
console.log(typeof [])//object
console.log(typeof null)//object
console.log(typeof undefined)//undefined
console.log(typeof {})//object
console.log(typeof function () {})//function
typeof
无法正确的区分object
,null
,array
2.instanceof (返回布尔值)
console.log(true instanceof Boolean)//false
console.log('' instanceof String)//false
console.log(1 instanceof Number)//false
console.log([] instanceof Object)//true
console.log([] instanceof Array)//true
console.log(null instanceof Object)//false
console.log(undefined instanceof Object)//false
console.log({} instanceof Object)//true
console.log(function () {} instanceof Function)//true
instanceof
后面跟数据类型,且大小写不能错
3.Object.prototype.toString.call(返回字符串)
个人比较喜欢这种的,可以直接返回任何你想要的类型,除了有点繁琐。
function getRawType(value) {
return Object.prototype.toString.call(value).slice(8,-1)
}
console.log(getRawType(true))//Boolean
console.log(getRawType(''))//String
console.log(getRawType(1))//Number
console.log(getRawType([]))//Array
console.log(getRawType(null))//Null
console.log(getRawType(undefined))//Undefined
console.log(getRawType({}))//Object
console.log(getRawType(function () {}))//Function
正则的妙用
1.横线转驼峰命名
let reg= /-(\w)/g;
function nameChange(str) {
return str.replace(reg,(_, c)=> c ? c.toUpperCase() : '')
}
console.log(nameChange('ab-cd-ef'))// abCdEf
2.驼峰转横线命名
let reg= /-(\w)/g;
function nameChange(str) {
return str.replace(reg,(_, c)=> c ? c.toUpperCase() : '')
}
console.log(nameChange('ab-cd-ef'))// abCdEf
3.交换单词
let reg= /(\w+)\s(\w+)/;
let str = "John Smith pull push";
let newstr = str.replace(reg, "$2 $1");
console.log(newstr);//Smith John pull push
这部分可以参考MDN的讲解
数组去重
1.数组方法
let arr = [1,1,1,2,2,2,2,3,3,3,'a','a','b','a']
function unique (arr) {
let result = []
arr.forEach(item => {
if (result.indexOf(item)==-1) result.push(item)
})
return result
}
console.log(unique (arr))//[1, 2, 3, "a", "b"]
2.对象方法
let arr = [1,1,1,2,2,2,2,3,3,3,'a','a','b','a']
function unique (arr) {
let arrobj = {}
arr.forEach(item => {
arrobj[item] = 1
})
return Object.keys(arrobj)
}
console.log(unique (arr))//[1, 2, 3, "a", "b"]
3.set方法
let arr = [1,1,1,2,2,2,2,3,3,3,'a','a','b','a']
function unique (arr) {
return [...new Set(arr)]
}
console.log(unique (arr))//[1, 2, 3, "a", "b"]
js动画
1.setInterval
通过定时器,每次去调用,如果上一个执行了很久会出现问题
2.requestAnimationFrame
性能好 可以看一下MDN的讲解
Vue中router的两种模式
hash(用到了hashChange)
优点:不需要后端配合前端就可以处理
缺点:微信解析时候可能出错(或者有的人会认为不好看)
history(history.pushState API)
缺点:需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 http://oursite.com/user/id 就会返回 404,这就不好看了。
解决办法:所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。
详情