ES5中的将伪数组转为数组中的Array.prototyp.slice.call(),的讲解

ES5中的将伪数组转为数组中的Array.prototyp.slice.call(),手写及讲解

Array.prototype.slice()

  • 返回值是一个新的数组
  • 参数1:切的起始位置,参数2:结束的位置(不包括)
let arr = [10,20,30,40,50,60];
console.log(arr.slice(2) === arr);//false

手写Array.prototype.slice()

Array.prototype.mySlice = function (index1,index2){
    
    
	if (!index1){
    
    
		index1 = 0
	}
	if (!index2){
    
    
		index2 = this.length
	}
	let i = index1;
	let arr = [];
	for (;i<index2;i++){
    
    
		arr.push(this[i]);
	}
	return arr
}

如果是这样的Array.prototype.mySlice.call(arguments)

Array.prototype.mySlice = function (index1,index2){
    
    
//this------------->arguments
	if (!index1){
    
    
		index1 = 0
	}
	if (!index2){
    
    
		index2 = this.length
	}
	let i = index1;
	let arr = [];
	for (;i<index2;i++){
    
    
		arr.push(this[i]); //this[i]---------->arguments[i]
	}
	return arr
}

所以在ES5中是用Array.prototype.slice来将伪数组转换为数组

猜你喜欢

转载自blog.csdn.net/webMinStudent/article/details/109172773