Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组push、pop方法模拟实现 #40

Open
conan1992 opened this issue Jun 28, 2020 · 0 comments
Open

数组push、pop方法模拟实现 #40

conan1992 opened this issue Jun 28, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

push

push() 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度

语法

arr.push(element1, ..., elementN)

参数

elementN: 被添加到数组末尾的元素。

返回值

当调用该方法时,新的 length 属性值将被返回

push模拟实现

Array.prototype.push2 = function(){
			let O = Object(this),len = O.length >>> 0;
			let argsLength = arguments.length >>> 0;
			let k = 0;
			while(argsLength--){
				O[len] = arguments[k++];
				len++;
			}
			return len;
		}
		var vegetables = ['parsnip', 'potato'];
		var moreVegs = ['celery', 'beetroot'];
		
		// 将第二个数组融合进第一个数组
		// 相当于 vegetables.push('celery', 'beetroot');
		Array.prototype.push2.apply(vegetables, moreVegs);
		
		console.log(vegetables); 

pop

pop()方法从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度

语法

arr.pop()

返回值

从数组中删除的元素(当数组为空时返回undefined)。

pop模拟实现

Array.prototype.pop2 = function(){
			let O = Object(this),len = O.length >>> 0;
			let result;
			if(len){
				len--;
				result = O[len];
				delete O[len]
				O.length = len;
			}
			
			
			return result;
		}
		var arr = [1,2,3];
		console.log( arr.pop2(), arr )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant