JS code - JavaScript 常见语法
Frontend
Json String
若现在有一个 JSON 对象的数组,可以使用的处理方法有:
-
JSON.stringify()处理 JSON 对象成为字符串
-
JSON.parse()处理字符串成为 JSON 对象
forEach()
如果需要对数组的遍历:
array.forEach(function(obj, index){
// ...
})
eval()
计算某个字符串,并执行其中的JS代码
var vm = new Vue({
el: '#app',
data: {
// ...
},
methods: {
calc() {
var codeStr = 'parseInt(this.n1)' + this.opt + 'parseInt(this.n2)'
this.result = eval(codeStr)
}
}
})
上述代码的作用是:从字符串中,计算出了result=n1+n2的表达式的值
Date and Time
JavaScript 中的时间操作:
var date = new Date()
// Thu Oct 25 2018 20:04:42 GMT+0800 (China Standard Time)
Date 的 functions:
date.toDateString()
//"Thu Oct 25 2018"
date.getMonth()
// 9 (0-11)
date.getFullYear()
//2018
Formatting
Vue.js filter: v-sample-github
filters: {
dateFormat: function (dateStr) {
var dt = new Date(dateStr)
var y = dt.getFullYear()
var m = (dt.getMonth() + 1).toString().padStart(2, '0')
var d = dt.getDate().toString().padStart(2, '0')
var hh = dt.getHours().toString().padStart(2, '0')
var mm = dt.getMinutes().toString().padStart(2, '0')
var ss = dt.getSeconds().toString().padStart(2, '0')
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}
// 2018-10-12 11:39:41
{{ time | dateFormat }}
Month Full Name
获取月份的完整拼写:
var date = new Date()
var month = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
monthString = month[date.getMonth()]
// October or any string
Split Date
split time string:
date.toDateString().slice(4, 11).replace(/ /, '-')
//"Oct-25 "
Timestamp
tranform date string to timestamp (将日期字符串转化成时间戳)
toTimeString(time) {
return time.replace(/[^0-9]/ig, "")
}
// 2018/11/20 10:36, Tuesday => 201811201036
Sort Date
对于时间进行排序:
computed: {
posts() {
return this.$site.pages
.filter(x => x.path.startsWith("/algorithm/"))
.sort((a, b) => Date.parse(b.lastUpdated) - Date.parse(a.lastUpdated))
}
}
Performance
性能分析:
console.time("My operation")
//code
console.timeEnd("My operation")
Var, Let and Const
修改历史9 次提交
- refactor: reorganize documentation structure and update Navbar componentxiaocheng··
2fb8f42 - chore(project): clean up obsolete configuration and build artifactsxiaocheng··
3574bd3 - new struct for lblogsxiaocheng··
8c9b28e - move blogs to docsxiaocheng··
c8535a0 - update codechenweigao··
e4c6887 - update fix: timeline errorchenweigao··
fb4b591 - update Datechenweigao··
3c14689 - init v3chenweigao··
b770fc2 - init v2chenweigao··
505f81b