深拷贝

  1. var cloneObj = function(obj){
  2. var str, newobj = obj.constructor === Array ? [] : {};
  3. if(typeof obj !== 'object'){
  4. return;
  5. } else if(window.JSON){
  6. str = JSON.stringify(obj), //系列化对象
  7. newobj = JSON.parse(str); //还原
  8. } else {
  9. for(var i in obj){
  10. newobj[i] = typeof obj[i] === 'object' ?
  11. cloneObj(obj[i]) : obj[i];
  12. }
  13. }
  14. return newobj;
  15. };

数组拍平

拍平数组(一层)

  1. const flatten = [1, [2, [3, [4]], 5]].reduce( (a, b) => a.concat(b), [])
  2. // => [1, 2, [3, [4]], 5]

拍平数组(完全)

  1. const flattenDeep = (arr) => Array.isArray(arr)
  2. ? arr.reduce( (a, b) => [...flattenDeep(a), ...flattenDeep(b)] , [])
  3. : [arr]
  4. flattenDeep([1, [[2], [3, [4]], 5]])
  5. // => [1, 2, 3, 4, 5]

node获取当前文件目录名称

  1. path.resolve(__dirname).split(path.sep).pop()

获取当前月份的第一天和最后一天

  1. function timeFormat (date) {
  2. if (!date || typeof (date) === 'string') {
  3. throw Error('参数异常,请检查...')
  4. }
  5. var y = date.getFullYear() //年
  6. var m = date.getMonth() + 1 //月
  7. var d = date.getDate() //日
  8. return y + '-' + m + '-' + d
  9. }
  10. function getMonthFirstDay () {
  11. var date = new Date()
  12. date.setDate(1)
  13. return timeFormat(date)
  14. }
  15. function getMonthLastDay () {
  16. var curDate = new Date()
  17. var curMonth = curDate.getMonth()
  18. curDate.setMonth(curMonth + 1)
  19. curDate.setDate(0)
  20. return timeFormat(curDate)
  21. }

JS判断字符串长度(英文占1个字符,中文汉字占2个字符)

  1. String.prototype.gblen = function() {
  2. var len = 0;
  3. for (var i=0; i<this.length; i++) {
  4. if (this.charCodeAt(i)>127 || this.charCodeAt(i)==94) {
  5. len += 2;
  6. } else {
  7. len ++;
  8. }
  9. }
  10. return len;
  11. }
  1. function strlen(str){
  2. var len = 0;
  3. for (var i=0; i<str.length; i++) {
  4. var c = str.charCodeAt(i);
  5. //单字节加1
  6. if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
  7. len++;
  8. }
  9. else {
  10. len+=2;
  11. }
  12. }
  13. return len;
  14. }
  1. var jmz = {};
  2. jmz.GetLength = function(str) {
  3. ///<summary>获得字符串实际长度,中文2,英文1</summary>
  4. ///<param name="str">要获得长度的字符串</param>
  5. var realLength = 0, len = str.length, charCode = -1;
  6. for (var i = 0; i < len; i++) {
  7. charCode = str.charCodeAt(i);
  8. if (charCode >= 0 && charCode <= 128) realLength += 1;
  9. else realLength += 2;
  10. }
  11. return realLength;
  12. };
  1. var l = str.length;
  2. var blen = 0;
  3. for(i=0; i<l; i++) {
  4. if ((str.charCodeAt(i) & 0xff00) != 0) {
  5. blen ++;
  6. }
  7. blen ++;
  8. }
  1. getBLen = function(str) {
  2. if (str == null) return 0;
  3. if (typeof str != "string"){
  4. str += "";
  5. }
  6. return str.replace(/[^\x00-\xff]/g,"01").length;
  7. }

原生ajax步骤

  1. function ajax(url, success, fail) {
  2. // 1. 创建连接
  3. const xhr = new XMLHttpRequest()
  4. // 2. 连接服务器
  5. // 规定请求的类型、URL 以及是否异步处理请求。
  6. xhr.open('get', url, true)
  7. // 发送信息至服务器时内容编码类型
  8. xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
  9. // 3. 发送请求
  10. xhr.send(null)
  11. // 4. 接受服务器响应数据
  12. xhr.onreadystatechange = function() {
  13. if (xhr.readyState === 4) {
  14. if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
  15. success(xhr.responseText)
  16. } else { // fail
  17. fail && fail(xhr.status)
  18. }
  19. }
  20. }
  21. }

驼峰式和下划线的转换

_驼峰转下划线

  1. const toLowerLine = function (str) {
  2. return str.replace(/\B([A-Z])/g, '_$1').toLowerCase()
  3. }

下划线转驼峰

  1. const toLowerLine = function (str) {
  2. return str.replace(/\B([A-Z])/g, '_$1').toLowerCase()
  3. }

整个对象进行转换

  1. const listFormatCamel = function (obj) {
  2. if (Array.isArray(obj)) {
  3. obj.forEach((v, i) => {
  4. listFormatCamel(v)
  5. })
  6. } else if (obj instanceof Object) {
  7. Object.keys(obj).forEach(key => {
  8. const newKey = toCamel(key)
  9. if (newKey !== key) {
  10. obj[newKey] = obj[key]
  11. delete obj[key]
  12. }
  13. listFormatCamel(obj[newKey])
  14. })
  15. }
  16. }

捕获未catch的错误

  1. window.addEventListener("unhandledrejection", function(promiseRejectionEvent) {
  2. // handle error here, for example log
  3. });

rem布局的新招式,用vw替代resize的监听方法

  1. // rem 单位换算:定为 75px 只是方便运算,750px-75px、640-64px、1080px-108px,如此类推
  2. $vw_fontsize: 75; // iPhone 6尺寸的根元素大小基准值
  3. @function rem($px) {
  4. @return ($px / $vw_fontsize ) * 1rem;
  5. }
  6. // 根元素大小使用 vw 单位
  7. $vw_design: 750;
  8. html {
  9. font-size: ($vw_fontsize / ($vw_design / 2)) * 100vw;
  10. // 同时,通过Media Queries 限制根元素最大最小值
  11. @media screen and (max-width: 320px) {
  12. font-size: 64px;
  13. }
  14. @media screen and (min-width: 540px) {
  15. font-size: 108px;
  16. }
  17. }
  18. // body 也增加最大最小宽度限制,避免默认100%宽度的 block 元素跟随 body 而过大过小
  19. body {
  20. max-width: 540px;
  21. min-width: 320px;
  22. }

函数必须传参的写法

  1. const isRequired = () => { throw new Error('param is required'); };
  2. const hello = (name = isRequired()) => { console.log(`hello ${name}`) };
  3. // This will throw an error because no name is provided
  4. hello();
  5. // This will also throw an error
  6. hello(undefined);
  7. // These are good!
  8. hello(null);
  9. hello('David');