如果我想从头开始编写pop函数最有效的方法是什么?主要问题还在于如何在没有弹出元素的情况下返回原始数组?
Array.prototype.pop = function () {
var myArray = this;
var length = myArray.length;
var element = myArray[length-1];
myArray = myArray.slice(0,length-1);
return element;
}
var hello = [1,2,3,4,5];
hello.pop();
5
console.log(hello)
[1, 2, 3, 4, 5]
答案 0 :(得分:1)
使用splice
代替slice
- slice
不修改原始数组,而splice
则修改原始数组。
那就是说,既然你要移除最后一个元素,那么它将是return myArray.splice(length-1,1);
...它本质上是return myArray.pop()
的别名。
或者,尝试:
var element = myArray[length-1];
myArray.length = length-1;
return element;
答案 1 :(得分:1)
短而甜蜜:
Array.prototype.foo = function(){
return this.splice(this.length-1)[0];
};
返回最后一个元素,如果为零,则返回undefined并修改数组本身。
答案 2 :(得分:0)
啊表现......为什么你需要那个polyfill? Array.prototype.pop得到广泛支持!无论如何我创建了一个小的perf测试来检查:http://jsperf.com/manual-pop
答案 3 :(得分:0)
for($x = 0; $x < count($cartArr); $x++){
echo 'paramArr.push("' . $cartArr[$x] . '");';
}