一些常用的方法等

2018-06-24 02:02:49来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

<!DOCTYPE html>
<html><head>

<body onselectstart="return false;">
<div id="content" class="content">
  <div class="touchArea">
    <p class="item-subtitle">长按事件</p>
    <div className="jubao">
      <Grid avg={2} className="more-gridlist">
        <Col>举报</Col>
        <Col>取消</Col>
      </Grid>
      <span></span>
    </div>
  </div>
</div>

  <input type="text" name="" id="search-key" value="" />
</body>

1//时间戳变成日期格式

function parseStandard(time, format) {
    let t = new Date(time);
    let tf = function(i) {
    return(i < 10 ? '0' : '') + i
};
return format.replace(/yyyy|MM|dd|hh|mm|ss/g, function(a) {
 switch(a) {
  case 'yyyy':
  return tf(t.getFullYear());

  case 'MM':
  return tf(t.getMonth() + 1);

  case 'mm':
  return tf(t.getMinutes());

  case 'dd':
  return tf(t.getDate());

  case 'hh':
  return tf(t.getHours());

  case 'ss':
  return tf(t.getSeconds());
  default:
  return
    }
    })
  }
console.log(parseStandard(1625648542516, "yyyy-MM-dd hh:mm:ss"))

2,时间友好显示

function getDate(date) {
   return date instanceof Date ?date :date &&new Date(date.replace(/\-/g, "/").replace(/T/g, " ").substr(0, 19));}

function getTime(date) {return typeof date === "number" ? date : getDate(date).getTime();}
const preMinute = 1000 * 60,preHour = preMinute * 60,preDay = preHour * 24,halfamonth = preDay * 15;

function friendlyTime(startDate, endDate) {
  if(!startDate) return "";
  const dates = getDate(startDate),
  start = getTime(dates),
  end = getTime(endDate || Date.now());
  if(isNaN(start)) return startDate;
  const det = end - start;
  if(det < preMinute) return "刚刚";
  else if(det < preHour) return Math.round(det / preMinute) + "分钟前";
  else if(det < preDay) return Math.round(det / preHour) + "小时前";
  else if(det < preDay * 7) return Math.round(det / preDay) + "天前";
  else if(dates.getFullYear() !== new Date().getFullYear()) return dates.format("yyyy-MM-dd hh:mm");
  else return parseStandard(dates, "yyyy-MM-dd hh:mm:ss");
}
//参数一 开始时间 参数二 与一相差时间
    console.log('friendlyTime', friendlyTime('2018-04-19T9:00:00', ''))

 

3半角转全角

function toDBC(txtstring) {
   var tmp = "";
  for(var i = 0; i < txtstring.length; i++) {
    if(txtstring.charCodeAt(i) == 32) {
    tmp = tmp + String.fromCharCode(12288);
  }
if(txtstring.charCodeAt(i) < 127) {
  tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
  }
}
return tmp;
}
console.log('半角转全角', toDBC('song'))

4获取AddDayCount天后的日期

function GetDateStr(days) {
  var dd = new Date();
    dd.setDate(dd.getDate() + days); //获取AddDayCount天后的日期
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1; //获取当前月份的日期
  var d = dd.getDate();
    m = (m < 10 ? '0' : '') + m;
    d = (d < 10 ? '0' : '') + d;
    console.log('年,月,日', y, m, d)
  return dd
}
console.log('获取3天后的日期', GetDateStr(3))

5保留2位小数并4舍5入方法

function toDecimal(x) {
  var f = parseFloat(x);
    if(isNaN(f)) {
    return;
  }
    f = Math.round(x * 100) / 100;
  return f;
}
console.log('保留2位小数并4舍5入方法', toDecimal(0.125))

6两个时间相差几小时 保留2位小数

function getHour(s1, s2) {
  var reDate = /\d{4}-\d{1,2}-\d{1,2} /;
  s1 = new Date((reDate.test(s1) ? s1 : '2017-1-1 ' + s1).replace(/-/g, '/'));
  s2 = new Date((reDate.test(s2) ? s2 : '2017-1-1 ' + s2).replace(/-/g, '/'));
  var ms = s2.getTime() - s1.getTime();
  console.log('ms', ms)
  if(ms < 0) return 0;
  return toDecimal(ms / 1000 / 60 / 60);
}
console.log('两个时间相差几小时', getHour('2018-04-24 15:10:00', '2018-04-24 16:00:00'))

7格式化时间日期


Date.prototype.Format = function(fmt) { //author: meizz
var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }
console.log('格式还日期', new Date().Format("yyyy-MM-dd hh:mm:ss"))

8数组去重

Array.prototype.unique3 = function() {
var res = [];
var json = {};
for(var i = 0; i < this.length; i++) {
console.log('数组啧啧啧', this[i], json[this[i]])
if(!json[this[i]]) {
console.log('json', json)
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}
console.log('数组去重', [1, 2, 12, 2, 1, 12, 2, 12, 3, 4, 6, 3].unique3())

9对数组数字进行排序

function sortNumber(a, b) {
return a - b
}
var arr = [10, 5, 40, 25, 1];

console.log('对数组数字大小进行排序', arr.sort(sortNumber))

10对象排序同时按照两种方式排序。需求是这样的:“active”为1的排在前面,“active”为0的排在后面,然后分别按照“name”的字母顺序进行排序

var arr = [

{
  "name": "Alfredo",
  "active": 0
}, {
  "name": "Alexander",
  "active": 0
}, {
  "name": "Ronald",
  "active": 1
}, {
  "name": "salvador",
  "active": 0
}, {
  "name": "Saryn",
  "active": 1
}

];

arr.sort(function(a, b) {
    return b.name < a.name;
  }).sort(function(a, b) {
    return b.active - a.active
  });
console.log('对象排序', arr)


11时间戳化时间

function formatDuring(mss) {
var days = parseInt(mss / (1000 * 60 * 60 * 24));
var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
var seconds = parseInt((mss % (1000 * 60)) / 1000);
return hours + "时" + minutes + "分" + seconds + "秒";
}
console.log('时间戳化时间', formatDuring(352425367425))


12设置随机字符

function createVerifyCode() {
var code = '';
var codeLength = 4;
//设置随机字符
  var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
  //循环codeLength
  for(var i = 0; i < codeLength; i++) {
    var index = Math.floor(Math.random() * 36);
    code += random[index];
    }
  return code;
}
console.log('随机数', createVerifyCode())

13验证手机号 邮箱

function isCellphone(value) {
  var CELLPHONE_REGEXP = /^1[3|4|5|7|8][0-9]{9}$/;
  value = value.replace(/\s/gi, "");
  return value && CELLPHONE_REGEXP.test(value);
}

function isEmail(value) {
  var EMAIL_REGEXP = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
  return value && EMAIL_REGEXP.test(value);
}
console.log('手机号', isCellphone('183216500'))
console.log('邮箱', isEmail('98184'))

 

var arrObj = [{a: 1,c: 2,d: 3}, {a: 2,c: 2,d: 4}]
console.log('筛选数组对象', arrObj.filter(c => c.a == 1))

14存在则去除,不存在则添加

var isExist = false;
var choseTimeNew = [

  {id: 1,time: '时间1'},

  {id: 2,time: '时间2'},

  {id: 1,time: '时间1'}

]
for(var i = 0; i < choseTimeNew.length; i++) {
  if((choseTimeNew[i].id == 1)) {
    choseTimeNew.splice(i, 1);
    isExist = true;
    break;
  }
 }
if(!isExist) {
    choseTimeNew.push({id: 3,time: '时间3'});
}
console.log('choseTimeNew', choseTimeNew)

15数组对象去重


var arr2 = [

{
  name: "name1",
  num: "1"
},
{
  name: "name2",
  num: "11"
},
{
  name: "name3",
  num: "12"
},
{
  name: "name4",
  num: "13"
},
{
  name: "name2",
  num: "1"
},
{
  name: "name6",
  num: "12"
}
]

function arrayUnique2(arr, name) {
    var hash = {};
      return arr.reduce(function(item, next) {
      hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
    return item;
  }, []);
}
console.log('根据name去重', arrayUnique2(arr2, "name"));
console.log('根据num去重', arrayUnique2(arr2, "num"));

16获取某年某月天数

function getLastDay(year, month) {
  var new_year = year; //取当前的年份 
  var new_month = month++; //取下一个月的第一天,方便计算(最后一天不固定) 
  if(month > 12) //如果当前大于12月,则年份转到下一年 
  {
    new_month -= 12; //月份减 
    new_year++; //年份增 
  }
    var new_date = new Date(new_year, new_month, 1);
  console.log('new_date', new_date) //取当年当月中的第一天
    return(new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate(); //获取当月最后一天日期 
}

17数组累加

console.log('时间', getLastDay('2018', '2')) //28
var arr = [1, 2, 3, 4, 5, 6];
  console.time("ruduce");
Array.prototype.ruduceSum = function() {
  for(var i = 0; i < 10000; i++) {
  return this.reduce(function(preValue, curValue) {
  console.log(preValue, curValue)
  return preValue + curValue;
});
}
}
  arr.ruduceSum();
  console.log('最终的值:' + arr.ruduceSum()); // 21 
  console.timeEnd("ruduce");

18长按事件

var _this = this;
var timeOutEvent = 0;
$(".touchArea .item-subtitle").on({
  touchstart: function(e) {
  $(".subarea .sub-commenting-item").find('.subjubao').css({
  display: 'none'
})
$(".subarea .sub-commenting-item p").css({
  backgroundColor: '#f5f5f5'
})
timeOutEvent = setTimeout(() => {
  longPress($(this))
}, 1000);
  e.preventDefault();
},
touchmove: function(e) {
// clearTimeout(timeOutEvent);
// timeOutEvent = 0;
},
  touchend: function(e) {
    clearTimeout(timeOutEvent);
    if(timeOutEvent != 0) {
      $(".touchArea").find('.jubao').css({
      display: 'none'
})
$(".touchArea .item-subtitle").css({
  backgroundColor: '#fff'
})
  console.log('点击', $(this).siblings('.jubao'))
}
  return false;
}
});

function longPress(_that) {
  timeOutEvent = 0;
  $(".touchArea").find('.jubao').css({
  display: 'none'
});
_that.css({
  backgroundColor: '#999'
})
_that.siblings('.jubao').css({
  display: 'block'
})
console.log('长按', $(this).siblings('.jubao'))
};

19输入法

var cpLock = false;
var _this = this;
$('#search-key').on('compositionstart', function() {
  cpLock = true;
});
$('#search-key').on('compositionend', function() {
  cpLock = false;
if(!cpLock) {
  console.log('查询')
  //中文输入法 当还是拼音时不执行这个地方,拼音转为汉字时执行
  // _this.props.contactStore.Result=[];
  // _this.props.dispatch(ContactAction.getContactList(localStorage.CompanyID,$('#search-key').val(),5));
}
});
$('#search-key').on('input', function() {
  if(!cpLock) {
  console.log('查询');
  //输入法 除了中文输入法 当输入任何字符时都执行
  // _this.props.contactStore.Result=[];
  // _this.props.dispatch(ContactAction.getContactList(localStorage.CompanyID,$('#search-key').val(),5));
}
});
</script>

20手机号码中间加*正则

'18321640664'.replace(/\d{4}(?=\d{4}$)/, '****')

</html>

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:预览github代码

下一篇:base64文件大小计算