for-in

for...in以任意顺序遍历一个对象的可枚举属性。所以for-in不适合用来迭代一个Array。同时,for-in是可以遍历对象中所有可枚举属性的,包括原型链上的可枚举属性。

let ret = [];
array.num = 6;  //  对象上直接添加属性
Array.prototype.num = 6;  // 原型链中添加属性
for(let i in array){
  ret.push(array[i])
}
console.log(ret)   //  [ 1, 2, 3, 4, 5, 6, 7 ]

  

如果可以地设置属性为不可枚举,那么for-in循环将不会遍历到这个属性

 

let ret = [];
Object.defineProperty(array,"num",{
  enumerable: false,  // 设置属性不可遍历
  value: 8
})
for(let i in array){
  ret.push(array[i])
}
console.log(ret)  //  [ 1, 2, 3, 4, 5 ]

 

解决方法:使用hasOwnProperty()
hasOwnProperty()方法可以检测一个属性是存在于实例中,还是存在于原型中。这个方法只在给定属性存在于对象实例中时,才会返回true。 

/数组
var arr = ["星期一","星期二","星期三"];
Array.prototype.something = ["放假","休息咯"];
for (var i in arr){
	if(arr.hasOwnProperty(i)){ 
		console.log(arr[i])
	}
}

  

for(最原始的写法)、 支持 break、continue和return语句)、

forEach 数组的方法,arr.forEach;  forEach(ES5,但是它不支持使用break、continue和return语句)、

for…in循环数组索引、对象的属性,但使用 for…in 原型链上的所有属性都将被访问,用 hasOwnProperty() 方法解决。

for…of(ES6,循环数组的元素值)这三个是循环数组(对象数组)的;

定义变量的6种方式

ES5 只有两种声明变量的方法:

var命令和function命令。

ES6 除了添加letconst命令,

还有 import命令和class命令。

ES6的两种方式

方法一 分析

function unique(arr) {
    //定义常量 res,值为一个Map对象实例
    const res = new Map();
    
    //返回arr数组过滤后的结果,结果为一个数组
    //过滤条件是,如果res中没有某个键,就设置这个键的值为1
    return arr.filter((a) => !res.has(a) && res.set(a, 1))
}

 

方法二:

 
function unique(arr) {
    return Array.from(new Set(arr))
}

两种还是有差异的,比如[2,,3,3]==>[2,3]/[2,3,undefined]

-----------------------

function unique(arr,prop){
         if(!prop){
         return [...new Set(arr)];
        }
    
         var result = [];
         var obj = {};
         for (var i =0; i<arr.length; i++){
          if (!obj[arr[i][prop]]){
            result.push(arr[i]);
            obj[arr[i][prop]] = true;
          }
         }
    return result;
}

 根据字符去重

uniqueArray(array, key) {
    var result = [array[0]];
    for (var i = 1; i < array.length; i++) {
        var item = array[i];
        var repeat = false;
        for (var j = 0; j < result.length; j++) {
            //console.log(item[key])
            if (item[key] == result[j][key]) {
                repeat = true;
                break;
            }
        }
        if (!repeat) {
            result.push(item);
        }
    }
    return result;
},
 var hasWords=[]
 uniqueArray(hasWords,"age");

数组中存在某个字段

function inArray(arr,item, val) {
    
      if(arr.length<=1){
       return false;
      }
      for(var i = 0; i < arr.length; i++) {
              console.log(arr[i]);
             if(arr[i][item] == val) {
 
                    return true;
 
             }
 
      }
 
      return false;
  };
   
   
  var arr2ss=[{sa:1,sb:1},{sa:2,sb:2}];
   
   
 var has2= inArray(arr2ss, "sa",2);
 console.log("has2",has2);

 

//例如,以下代码会输出5次,结果都是5,那么如何输出0、1、2、3、4?
 
 for(var i = 0; i < 5; i++) {
       setTimeout(function() {
              console.log(i);
        }, 1000);
 }
//利用闭包的原理实现,代码如下:
 
 for(var i = 0; i < 5; i++) {
         (function(e) {
                setTimeout(function() {
                    console.log('传进来的是'+e);
                }, 1000);
        })(i);
} 

  

es6 字符串

 $("#result").append(
        `He is <b>${person.name}</b>and we wish to know his${person.age}.that is all`
        );

  

:prop="`list.${index2}.tableData.${scope.$index}.input`" 

 

 

js 数据类型判断 iview

function typeOf(obj) {
    const toString = Object.prototype.toString;
    const map = {
        '[object Boolean]'  : 'boolean',
        '[object Number]'   : 'number',
        '[object String]'   : 'string',
        '[object Function]' : 'function',
        '[object Array]'    : 'array',
        '[object Date]'     : 'date',
        '[object RegExp]'   : 'regExp',
        '[object Undefined]': 'undefined',
        '[object Null]'     : 'null',
        '[object Object]'   : 'object'
    };
    return map[toString.call(obj)];
}

  

 

es6 剩余参数

function setData(index,howmany){
	           
	         		  var arg=arguments;
	         		  var index=arg[0]; 
	                  var howmany=arg[1];
	         		  var newList =[].slice.call(arguments).filter(function (item,index) {
	                      return index>1;
	                    });

                       //var args = [].slice.call(arguments)
                       // 避免泄露参数 参数是执行数组方法时括号中的参数
                       // http://jsperf.com/closure-with-arguments
                       //  let i = arguments.length
                       //  var args = new Array(i)
                       //  while (i--) {
                       //    args[i] = arguments[i]
                       //  }
                       	         
                       // 从第二个参数开始处理(数组下标1)
                       //	 for (var  i = 2, len = arguments.length; i < len; i++) {
                       //	result[arguments[i]] = object[arguments[i]]
                       //	}
                          
                       // 子类续承父类
                       //Rectangle.prototype = Object.create(Shape.prototype);
                       //Rectangle.prototype.constructor = Rectangle;
}

  

function func(a,b ...rest) {
  console.log(a)
  console.log(rest)
}
func(1)
func(1, 2, 3, 4)

 替换整个数组

 var ar2r=[1,2,3]
	     ar3r=[4,5,6]
	     ar2r.splice(0,ar2r.length,...ar3r)
		 console.log("ar2r",ar2r)

  

 

for  /while    循环 省略

var cars=["BMW","Volvo","Saab","Ford"];
 
for (var i=cars.length;i--;)
{
    console.log(cars[i] + "<br>");
 
}
 
var cars0=["BMW0","Volvo0","Saab0","Ford0"];
 
for (var i=0;i<cars0.length;i++)
{
    console.log(cars0[i] + "<br>");
 
}
 
 var cars=["BMW1","Volvo1","Saab1","Ford1"];
var i=0;
for (;cars[i];)
{
    console.log(cars[i] + "<br>");
    i++;
}
 
var cars2=["BMW2","Volvo2","Saab2","Ford2"];
var i=0;
while (cars2[i])
{
    console.log(cars2[i] + "<br>");
    i++;
}
 
var cars3=["BMW3","Volvo3","Saab3","Ford3"];
var i=cars3.length;
while (i--)
{
    console.log(cars3[i] + "<br>");
 
}

  

 获取css3 translate 属性

function getTransform(el) {  //获取translate
       var transform =  window.getComputedStyle(el, null).getPropertyValue('-webkit-transform')|| window.getComputedStyle(el, null).getPropertyValue('transform');
       var matrix = transform.match(/matrix(3d)?\((.+?)\)/);
         var is3D = matrix && matrix[1];
         if (matrix) {
             matrix = matrix[2].split(",");
             if (is3D === "3d")
                 matrix = matrix.slice(12, 15);
             else {
                 matrix.push(0);
                 matrix = matrix.slice(4, 7);
             }
         } else {
             matrix = [0, 0, 0];
         }
         var result = [
              Number(matrix[0]),
              Number(matrix[1]),
              Number(matrix[2])
         ];
     console.log("result",result)
         return result;
 }

 

 

判断json 

var isJson = function(obj){
            var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length
            return isjson;
        }
 
 var isEmptyObject=function(obj){
            for(var n in obj){return false}
             return true;
   }

  

移动端 键盘事件

onCompositionStart以及onCompositionEnd

  

 两个dom 是否相同

所谓相同,指的是两个节点引用的是同一个对象;

所谓相等,指的是两个节点是否是同一类型,具有相等的属性(nodeName,nodeValue。。。等等),还有相等的attributes,childNodes(相同的位置包含相同的值)

语法:

 

node1.isSameNode(node2) 
node1.isEqualNode(node2)

  

 

formatDate

function formatDate(date) {
  var d = new Date(date),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();
  
  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;
  
  return [year, month, day].join('-');
}
 console.log(formatDate('Sun May 13,2016'))

  

toFormatNumber

function  toFormatNumber(event,itemprops,item,minVal){
 
      var item2=item;
      var result= item2[itemprops]||"";
            result = result.toString().replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符 
              result = result.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的 
          result = result.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
          result= result.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数 
            if(result.indexOf(".")< 0 && result !=""){//以上已经过滤,此处如果没有小数点,首位不能为类似于 01、02的金额
                result= parseFloat(result);
            }
             
 
            if(minVal&&result<minVal){
                result=minVal;
    }
        this.$set(item2,itemprops,result);
    };
 

数组字符串

var str2 = "0123456789";
console.log(str2.slice(4,7));       //----------"456"
 
var arrs=[0,1,2,3,4,5,6,7,8,9];
console.log(arrs.slice(4,7));   //----------"[4,5,6]"

var test = 'hello world';
console.log(test.slice(4,7));             //o w
console.log(test.substring(4,7));         //o w
console.log(test.substr(4,7));            //o world
 
//需要注意的地方就是:substring是以两个参数中较小一个作为起始位置,较大的参数作为结束位置。
console.log(test.substring(7,4))

 

变量 提升 作用域

var msg1='This is message 1';  
var msg3='This is message 3';  
function otherFunction()  
{  
    msg2='This is message 2'; //不使用var关键字,-其实也是定义一个全局变量  
    var msg3='Message 3';  
    var ms4='Message 4';
    alert(msg1); //This is message 1 (-函数内当然可以访问到外面定义的全局变量,再深的函数嵌套一样能正确获到这个全局变量,这是JavaScript闭包的其中一种体现)  
    alert(msg3); //Message 3 (局部变量msg3)  
    alert(window.msg3); //This is message 3 (-使用window前缀访问同名的全局变量msg3)  
    alert(this.msg3); //This is message 3 (-因为otherFunction ()定义在一个全局的环境中,此时otherFunction ()的this也是指向window,所有你看到window. msg3是等于this. msg3的)  
}  
otherFunction();  
//otherFunction-函数外面定义的msg1和里面定义的msg2依然是全局变量  
alert(window.msg1); //-- This is message 1  
alert(window.msg2); //-- This is message 2  
alert(window.ms4); // -- underfind       外部不可以访问内部

 new操作符创建对象

 一般来说,new操作符创建对象可以分为四个步骤:
1. 创建一个空对象
2. 将所创建对象的__proto__属性值设成构造函数的prototype属性值
3. 执行构造函数中的代码,构造函数中的this指向该对象
4. 返回该对象(除非构造函数中返回一个对象)并且最后隐式的返回 this 。
用代码表示如下:

function Person(a, b) {
  this.name = a;
  this.age = b;
}

Person.prototype.show = function() {
  console.log(this.name, this.age);
};

// var p = new Person('address', 10);
var p = {};
p.__proto__ = Person.prototype;
Person.call(p, 'address', 10);

console.log(p);

封装一下 大致如此

function realizeNew () {
    //创建一个新对象
    let obj  = {};
    //获得构造函数
    let Con = [].shift.call(arguments);
    //链接到原型(给obj这个新生对象的原型指向它的构造函数的原型)
    obj.__proto__ = Con.prototype;
    //绑定this
    let result = Con.apply(obj,arguments);
    //确保new出来的是一个对象
    return typeof result === "object" ? result : obj
} 

 

 

js错误类型

Error对象有两个最基本的属性:

name:错误名称
message:错误提示信息

除了Error对象,JavaScript还定义了其他6种错误,即存在Error的6个衍生对象

EvalError:执行代码时发生的错误
RangeError:当一个数值型变量或参数超出有效范围时发生的错误
ReferenceError:引用一个不存在的变量时发生的错误
SyntaxError:解析代码时发生的语法错误
TypeError:变量或参数的类型无效时发生的错误
URIError:向encodeURI() 或者 decodeURI() 传入无效参数时发生的错误

js 命名规范

s:表示字符串。例如:sName,sHtml;
n:表示数字。例如:nPage,nTotal;
b:表示逻辑。例如:bChecked,bHasLogin;
a:表示数组。例如:aList,aGroup;
r:表示正则表达式。例如:rDomain,rEmail;
f:表示函数。例如:fGetHtml,fInit;
o:表示以上未涉及到的其他对象,例如:oButton,oDate;
g:表示全局变量,例如:gUserName,gLoginTime;
 
 

匿名函数写法


//五大类
 
//第一类
//最常见的一种
( function(w) {
    alert(w.location.href+","+11);
}(window));
 
[ function(w) {
    alert(w.location.href+","+11);
}(window) ];
 
//第二类
~ function(w) {
    alert(w.location.href+","+11);
}(window);
 
! function(w) {
    alert(w.location.href+","+11);
}(window);
 
+ function(w) {
    alert(w.location.href+","+11);
}(window);
 
- function(w) {
    alert(w.location.href+","+11);
}(window);
 
//第三类
delete function(w) {
    alert(w.location.href+","+11);
}(window);
 
typeof function(w) {
    alert(w.location.href+","+11);
}(window);
 
void function(w) {
    alert(w.location.href+","+11);
}(window);
 
new function(w) {
    alert(w.location.href+","+11);
}(window);
 
new function() {
    alert(window.location.href+","+11);
}; 
 
//第四类
var f = function(w) {
    alert(w.location.href+","+11);
}(window);
 
//第五类
1, function() {
    alert(window.location.href+","+11);
}();
 
1 ^ function() {
    alert(window.location.href+","+11);
}();
 
1 > function() {
    alert(window.location.href+","+11);
}();
 
1 < function() {
    alert(window.location.href+","+11);
}();
 
1 / function() {
    alert(window.location.href+","+11);
}();
 
1 * function() {
    alert(window.location.href+","+11);
}();
 
1 | function() {
    alert(window.location.href+","+11);
}();
 
1 % function() {
    alert(window.location.href+","+11);
}();
 
1 & function() {
    alert(window.location.href+","+11);
}();

 

获取元素尺寸

 /**
    * Get element size
    * @param {HTMLElement} element
    * @returns {Object} {width, height}
    */
    function getElementSize(element) {
        if (!element.getBoundingClientRect) {
            return {
                width: element.offsetWidth,
                height: element.offsetHeight
            }
        }

        var rect = element.getBoundingClientRect();
        return {
            width: Math.round(rect.width),
            height: Math.round(rect.height)
        }
    }

dom 变化2

 

// http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/
(function(){
  var attachEvent = document.attachEvent;
  var isIE = navigator.userAgent.match(/Trident/);
  console.log(isIE);
  var requestFrame = (function(){
    var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
        function(fn){ return window.setTimeout(fn, 20); };
    return function(fn){ return raf(fn); };
  })();
  
  var cancelFrame = (function(){
    var cancel = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame ||
           window.clearTimeout;
    return function(id){ return cancel(id); };
  })();
  
  function resizeListener(e){
    var win = e.target || e.srcElement;
    if (win.__resizeRAF__) cancelFrame(win.__resizeRAF__);
    win.__resizeRAF__ = requestFrame(function(){
      var trigger = win.__resizeTrigger__;
      trigger.__resizeListeners__.forEach(function(fn){
        fn.call(trigger, e);
      });
    });
  }
  
  function objectLoad(e){
    this.contentDocument.defaultView.__resizeTrigger__ = this.__resizeElement__;
    this.contentDocument.defaultView.addEventListener('resize', resizeListener);
  }
  
  window.addResizeListener = function(element, fn){
    if (!element.__resizeListeners__) {
      element.__resizeListeners__ = [];
      if (attachEvent) {
        element.__resizeTrigger__ = element;
        element.attachEvent('onresize', resizeListener);
      }
      else {
        if (getComputedStyle(element).position == 'static') element.style.position = 'relative';
        var obj = element.__resizeTrigger__ = document.createElement('object'); 
        obj.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
        obj.__resizeElement__ = element;
        obj.onload = objectLoad;
        obj.type = 'text/html';
        if (isIE) element.appendChild(obj);
        obj.data = 'about:blank';
        if (!isIE) element.appendChild(obj);
      }
    }
    element.__resizeListeners__.push(fn);
  };
  
  window.removeResizeListener = function(element, fn){
    element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);
    if (!element.__resizeListeners__.length) {
      if (attachEvent) element.detachEvent('onresize', resizeListener);
      else {
        element.__resizeTrigger__.contentDocument.defaultView.removeEventListener('resize', resizeListener);
        element.__resizeTrigger__ = !element.removeChild(element.__resizeTrigger__);
      }
    }
  }
})();
//
// var myElement = document.getElementById('my_element'),
//     myResizeFn = function(){
//         /* do something on resize */
//     };
// addResizeListener(myElement, myResizeFn);
// removeResizeListener(myElement, myResizeFn);

  

--

function resizeObserver(ele,fn,self){
	//MutationObserver、IntersectionObserver、ResizeObserver
     var dom=ele;
 	 var self=self||this;;

    // window.ResizeObserver=false;
 	 if(window.ResizeObserver){//resize-observer-polyfill
 	 var myObserver = new ResizeObserver(function(entries) {
		 
		    if(dom.tick){
		     	clearTimeout(dom.tick)
		    }
		    dom.tick=setTimeout(function(){	   					   		
		     	entries.forEach(function(entry){
					entry.offsetHeight=entry.borderBoxSize[0].blockSize||dom&&dom.offsetHeight;
					entry.offsetWidth=entry.borderBoxSize[0].inlineSize||dom&&dom.offsetWidth;
					//console.log("原生 ResizeObserver",entry,'version',self.version)

		     	 	fn&&fn.call(null,entry,self)
		     	  })
		    },12)
 	     })
 		   myObserver.observe(dom)
		 
 		 }else{   // polyfill  兼容处理
			   
			       addResizeListener(ele,function(e){
						var entry={
							offsetHeight:dom.offsetHeight,
							offsetWidth:dom.offsetWidt,
						};
					// console.log("自定义 addResizeListener",entry,'version',self.version)
						fn&&fn.call(null,entry,self)
					})
 		}

 }

  

 

监听dom 变化

//ResizeSensor.js is part of a huge library, but I reduced its functionality to THIS:
 //https://stackoverflow.com/questions/6492683/how-to-detect-divs-dimension-changed/19418065#19418065
 //var container = document.querySelector(".container");
// new ResizeSensor(container, function()
// {
//     console.log("dimension changed:", container.clientWidth, container.clientHeight);
// });



 function ResizeSensor(element, callback)
 {
     var zIndex = parseInt(getComputedStyle(element));
     if(isNaN(zIndex)) { zIndex = 0; };
     zIndex--;
 
     var expand = document.createElement('div');

     // expand.style.position = "absolute";
     // expand.style.left = "0px";
     // expand.style.top = "0px";
     // expand.style.right = "0px";
     // expand.style.bottom = "0px";
     // expand.style.overflow = "hidden";
     // expand.style.zIndex = zIndex;
     // expand.style.visibility = "hidden";
	 
	 setStyle(expand,{
	 	"position":"absolute",
	 	"left":"0px",
	 	"top":"0px",
	 	"right":"0px",
	 	"bottom":"0px",
		"overflow":"hidden",
	 	"zIndex":zIndex,
	 	"visibility":"hidden",
	 })
 
     var expandChild = document.createElement('div');
     // expandChild.style.position = "absolute";
     // expandChild.style.left = "0px";
     // expandChild.style.top = "0px";
     // expandChild.style.width = "10000000px";
     // expandChild.style.height = "10000000px";
	 
	 setStyle(expandChild,{
	 	"position":"absolute",
	 	"left":"0px",
	 	"top":"0px",
	 	"width":"10000000px",
	 	"height":"10000000px",
	 })
	 
     expand.appendChild(expandChild);
	 

     var shrink = document.createElement('div');
     // shrink.style.position = "absolute";
     // shrink.style.left = "0px";
     // shrink.style.top = "0px";
     // shrink.style.right = "0px";
     // shrink.style.bottom = "0px";
     // shrink.style.overflow = "hidden";
     // shrink.style.zIndex = zIndex;
     // shrink.style.visibility = "hidden";
	 
	 setStyle(shrink,{
	 	"position":"absolute",
	 	"left":"0px",
	 	"top":"0px",
	 	"right":"0px",
	 	"bottom":"0px",
	    "overflow":"hidden",
	 	"zIndex":zIndex,
	 	"visibility":"hidden",
	 })
	 

     var shrinkChild = document.createElement('div');
     // shrinkChild.style.position = "absolute";
     // shrinkChild.style.left = "0px";
     // shrinkChild.style.top = "0px";
     // shrinkChild.style.width = "200%";
     // shrinkChild.style.height = "200%";
	 
	 setStyle(shrinkChild,{
	 	"position":"absolute",
	 	"left":"0px",
	 	"top":"0px",
	 	"width":"200%",
	 	"height":"200%",
	 })
	 
	 
	 
     shrink.appendChild(shrinkChild);
 
     element.appendChild(expand);
     element.appendChild(shrink);
 
     function setScroll()
     {
         expand.scrollLeft = 10000000;
         expand.scrollTop = 10000000;
 
         shrink.scrollLeft = 10000000;
         shrink.scrollTop = 10000000;
     };
     setScroll();
 
     var size = element.getBoundingClientRect();
 
     var currentWidth = size.width;
     var currentHeight = size.height;
 
     var onScroll = function()
     {
         var size = element.getBoundingClientRect();
         var newWidth = size.width;
         var newHeight = size.height;
        
         if(newWidth != currentWidth || newHeight != currentHeight)
         {
             currentWidth = newWidth;
             currentHeight = newHeight;
 
             size.height=size.height||size.bottom - size.top||element.offsetHeight;
             size.width=size.width||size.right - size.left||element.offsetWidth;
			 // console.log("element",element)
			 // size.scrollTop=this.scrollTop;
             callback(size);
			
			
         }
 
         setScroll();
     };
 
     expand.addEventListener('scroll', onScroll);
     shrink.addEventListener('scroll', onScroll);
	 function setStyle(eleObj, cssObj) {
	        for (var property in cssObj) {
	            eleObj.style[property] = cssObj[property];
	        };
	  }
 };
 
 
 
 

  

 调用

function resizeObserver(ele,fn,self,timer){
	//MutationObserver、IntersectionObserver、ResizeObserver
     var dom=ele;
 	 var self=self||this;;

    // window.ResizeObserver=false;
 	 if(window.ResizeObserver){//resize-observer-polyfill
 	 var myObserver = new ResizeObserver(function(entries) {
		 
		    if(dom.tick){
		     	clearTimeout(dom.tick)
		    }
		    dom.tick=setTimeout(function(){	   					   		
		     	entries.forEach(function(entry){
					
					// 这里的entry.target是DOM节点本身,而entry.contentRect是一个对象,包含了节点的位置属性,如width, height, left, right, bottom, left, x, y等。
					// width:指元素本身的宽度,不包含padding,border值
					// height:指元素本身的高度,不包含padding,border值
					//offsetHeight = content + padding + border = 200 + 20 * 2 + 2 * 2 = 244
					//clientHeight = content + padding = 200 + 20 * 2 = 240
				
					entry.offsetHeight=entry.borderBoxSize[0].blockSize||dom&&dom.offsetHeight;
					entry.offsetWidth=entry.borderBoxSize[0].inlineSize||dom&&dom.offsetWidth;
					//console.log("原生 ResizeObserver",entry,'version',self.version)

		     	 	fn&&fn.call(null,entry,self)
		     	  })
		    },timer||12)
 	     })
 		   myObserver.observe(dom)
		 
 		}else{   // polyfill  兼容处理
			      
			        if(ResizeSensor){
			   					   new ResizeSensor(dom, function(entry){
			   					       if(dom.tick){
			   					          clearTimeout(dom.tick)
			   					       }
			   					       dom.tick=setTimeout(function(){
			   					   		   
											entry.offsetHeight=entry.height||dom&&dom.offsetHeight;;
											entry.offsetWidth=entry.width||dom&&dom.offsetWidth;
											//console.log("我的 ResizeSensor",entry,'version',self.version)
			   					        	fn&&fn.call(null,entry,self) 
			   					       },timer||12)
			                         });
					
			         }else{
				   

						     var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
						     if(MutationObserver){// ie 

								   var MutationObserverConfig={
									   childList: true,
									   subtree: true,
									   characterData: true
								   };
								   var observer=new MutationObserver(function(entry){
									   
									   if(dom.tick){
									    	clearTimeout(dom.tick)
									   }
									   dom.tick=setTimeout(function(){
												entry.offsetHeight=dom.offsetHeight;
												entry.offsetWidth=dom.offsetWidth;
												//console.log("ie MutationObserver",entry,'version',self.version)
												fn&&fn.call(null,entry,self) 
										 },timer||12)
								   });
								   observer.observe(dom,MutationObserverConfig);
								  
								
							 }else{
									// dom.addEventListener("DOMSubtreeModified",function(entry){
									// 	 if(dom.tick){
									// 		 clearTimeout(dom.tick)
									// 	 }
									// 	 dom.tick=setTimeout(function(){
									// 		fn&&fn.call(null,entry,self) 
									// 	 },timer*8||100) 
									// }, false);
								}	
			}
 		}

 }

---

var dom=document.querySelector(".scroll-height");
		        resizeObserver(dom,function(entry,self){
					

					// console.log('2entry', entry)

					    if(entry&&entry.offsetHeight){
				        	var total= 	Math.ceil(entry.offsetHeight)  ;
					        self.maxScrollHeight=total-self.viewHeight;
						    dom.setAttribute("scroll-height",self.maxScrollHeight)
							dom.setAttribute("max-total",total)
						     self.setOneH()
							  // console.log('检测 entry', entry)	
							if(clickTop){
								self.setTop(clickTop);
							}
						  
						
					       // console.log('clickTop',clickTop,'1有1 entry 检测dom 变化',self.maxScrollHeight)
					      }else{
							  //ie 
							   var total=Math.ceil(dom.offsetHeight);
							       self.maxScrollHeight=total-self.viewHeight;
							       dom.setAttribute("scroll-height",self.maxScrollHeight) //ie 不可以设置
								   dom.setAttribute("max-total",total)
								    self.setOneH()
								   if(clickTop){
								   		self.setTop(clickTop);
								   }
								  
							      // console.log('clickTop',clickTop,'0无0 entry  检测dom 变化',self.maxScrollHeight)	 
						  }
					
				},self); 

  

 //MutationObserver、IntersectionObserver、ResizeObserver

intersection-observer-polyfill 

 

  observe(target) {
        if (!arguments.length) {
            throw new TypeError('1 argument required, but only 0 present.');
        }

        if (!(target instanceof Element)) {
            throw new TypeError('parameter 1 is not of type "Element".');
        }

        let targets = this._targets;

        // Do nothing if target is already observed.
        if (targets.has(target)) {
            return;
        }

        // Create new IntersectionObservation instance and assign it
        // to provided target.
        targets.set(target, new IntersectionObservation(target, this));

        // Connect current observer to controller
        // if it wasn't connected yet.
        if (!this.controller.isConnected(this)) {
            this.controller.connect(this);
        }

        // Request the update of observers.
        this.controller.startUpdateCycle();
    }

 

 elementui resize-event.js

import ResizeObserver from 'resize-observer-polyfill';
import { debounce } from 'throttle-debounce';

const isServer = typeof window === 'undefined';

/* istanbul ignore next */
const resizeHandler = function(entries) {
  for (let entry of entries) {
    const listeners = entry.target.__resizeListeners__ || [];
    if (listeners.length) {
      listeners.forEach(fn => {
        fn();
      });
    }
  }
};

/* istanbul ignore next */
export const addResizeListener = function(element, fn) {
  if (isServer) return;
  if (!element.__resizeListeners__) {
    element.__resizeListeners__ = [];
    element.__ro__ = new ResizeObserver(debounce(16, resizeHandler));
    element.__ro__.observe(element);
  }
  element.__resizeListeners__.push(fn);
};

/* istanbul ignore next */
export const removeResizeListener = function(element, fn) {
  if (!element || !element.__resizeListeners__) return;
  element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);
  if (!element.__resizeListeners__.length) {
    element.__ro__.disconnect();
  }
};

 使用

//先引入
import { addResizeListener, removeResizeListener } from 'utils/resize-event';

export default {
  mounted(){
    //可以在mounted这个钩子里初始化事件
    addResizeListener(this.$el, this.resizeListener);
  },
  methods:{
    resizeListener(){
      //do something
    }
  },
  //生命周期结束时销毁事件
  destroyed() {
    if (this.resizeListener) removeResizeListener(this.$el, this.resizeListener);
  }
}

  

 

空对象

const isEmpty = function(val) {
  // null or undefined
  if (val == null) return true;

  if (typeof val === 'boolean') return false;

  if (typeof val === 'number') return !val;

  if (val instanceof Error) return val.message === '';

  switch (Object.prototype.toString.call(val)) {
    // String or Array
    case '[object String]':
    case '[object Array]':
      return !val.length;

    // Map or Set or File
    case '[object File]':
    case '[object Map]':
    case '[object Set]': {
      return !val.size;
    }
    // Plain Object
    case '[object Object]': {
      return !Object.keys(val).length;
    }
  }

  return false;
};

 

 数组 比较

    //判断新旧数组 返回新数组相对老数组 增加数据
               function returnAddData(oldArr, newArr) {
               var obj = {};
               var index; //记录新数组中的索引
               for (var i = 0; i < newArr.length; i++) {
				
				  var sam=  oldArr.some(function( item, index, array ){ 
						   return JSON.stringify(newArr[i]) === JSON.stringify(item)
				 })
               if (sam) {
               } else {
               index = i;
               }
               if (index !== undefined) obj[index] = newArr[index];
               }
               return Object.values(obj);
               }
     
				
				
				//判断新旧数组 返回新数组相对老数组删除数据
				function returnDeleteData(oldArr, newArr) {
				var obj = {};
				var index; //记录老数组中的索引
				for (var i = 0; i < oldArr.length; i++) {
				var sam=newArr.some( function( item, index, array ){ 
					    return JSON.stringify(oldArr[i]) === JSON.stringify(item); 
					})
					
					
				if (sam) {
					
				} else {
				index = i;
				}
				if (index !== undefined) obj[index] = oldArr[index];
				}
				return Object.values(obj);
				}

  

其他。。。

  

 

相关文章: