js中apply(thisArg, [argsArray])的参数与ArrayLike的关系

你是否写过或见到过这样的代码
xx.apply(this,slice.call(arguments)) //slice.call转为数组是否多余
一、微软和mdn对参数的介绍
  • msdn上写的是一组参数(A set of arguments to be passed to the function.)
  • mdn写的就很清楚了是“An array-like object”,即类似数组。
二、什么是类数组
  • 具有length,键值为int型,可循环。如jQuery的isArrayLike方法
unction isArraylike( obj ) {
    var length = obj.length,
    	type = jQuery.type( obj );

	if ( type === "function" || jQuery.isWindow( obj ) ) {
		return false;
	}
    //node
	if ( obj.nodeType === 1 && length ) {
		return true;
	}
    //是数组||length=0||length为number同时具有length-1的键
	return type === "array" || length === 0 ||
		typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
  • 根据ArrayLike,可以验证以下的代码
console.log.apply(console,{0:'a',1:'b',length:2});// a b 在某些浏览器会报错
console.log.apply(console,document.querySelectorAll('div'));// div div .....
(function(){ console.log.apply(console,arguments)  })(window,[1,2,3]);// window [1,2,3]
  • 若length与数据真实键值不对应,还是根据循环来处理
console.log.apply(console,{0:'a',4:'b',b:0,length:5});//a undefined undefined undefined b 

三、兼容性?mdn上写了如下

Most browsers, including Chrome 14 and Internet Explorer 9, still do not accept array-like objects and will throw an exception.

  • chrome14 ie9与ie9以下传入object参数会报 “Function.prototype.apply: 缺少 Array 或 arguments 对象”的错误,错误事例
   XXX.apply(window,{0:'a',1:'b',length:2})// ERROR Function.prototype.apply: 缺少 Array 或 arguments 对象

四、对于apply来说,非自定义的ArrayLike,可与忽略toArray这一步操作

原文地址:https://www.cnblogs.com/henryli/p/3654159.html