js技巧一

时间格式化

1
2
3
4
5
6
7
8
9
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

个位数前面填充一个0

1
2
3
4
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}

根据下标删除数组元素

1
2
3
const removeItem = (arr, index) => {
arr.splice(index, 1)
}

从数组中删除指定的一个元素

1
2
3
4
5
6
const removeItem = (arr, val) => {
var index = arr.indexOf(val);
if (index > -1) {
arr.splice(index, 1);
}
}

从数组中删除指定的多个元素

1
2
3
4
5
6
const arrRemoves = (arr, val) => {
var newIndexs = val.map(function(val, idx){return val - idx})
newIndexs.forEach(function(index){
arr.splice(index, 1)
})
}

数组根据对象属性排序

1
2
3
4
5
6
7
var arr=[{name:"rose", id:3},{name:"jack",id:1},{name:"mafy"id:2}]
function rule(key) {
return function (a, b) {
return a[key] - b[key]
}
}        
arr.sort(rule("id"))

随机打乱数组顺序

1
2
3
4
5
var arr = [1, 2, 3, 4, 5, 6];
function randomsort(a, b) {
return Math.random() > .5 ? -1 : 1
}
arr.sort(randomsort)

手机号码加*号

1
2
3
4
5
var phone = 13834236433;
function addStar(phone) {
return phone.substr(0, 3) + '****' + phone.substr(-4, 4);
}
addStar(phone);

根据数组对象元素id去重

1
2
3
4
5
6
7
8
9
10
11
12
function uniarr (arr) {
var hash = [];
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i].id == arr[j].id) {
++i;
}
}
hash.push(arr[i]);
}
return hash;
}

重复字符串N次

1
2
3
var times = function(str, num) {
return num > 1 ? str += times(str, --num) : str;
}

图片流插件

https://github.com/desandro/masonry

图片轮播图插件

  • swiper.js
  • 轮播图 https://github.com/stevenwanderski/bxslider-4

浏览器拷贝粘贴插件

[拷贝粘贴] (https://github.com/zenorocha/clipboard.js)`https://github.com/zenorocha/clipboard.js`

在浏览器中打开微信

<a herf="weixin://"></a>

日期选择器

日期选择器 https://github.com/ddd702/datePicker

地址选择器

地址选择器 https://github.com/nzbin/Framework7-CityPicker

赞 赏
微信扫一扫