push()的相反操作是什么?

225

JavaScript中push();方法的相反方法是什么?

假设我有一个数组:

var exampleArray = ['remove'];

我想要 push(); 单词 'keep' -

exampleArray.push('keep');

我如何从数组中删除字符串'remove'


5
你可以在MDN文档中找到所有数组方法的列表:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array - Felix Kling
首先,找到您想要删除的元素的索引:var array = [2, 5, 9]; var index = array.indexOf(5); 注意:indexOf 的浏览器支持有限;它不支持 Internet Explorer 7 和 8。然后使用 splice 删除它:if (index > -1) { array.splice(index, 1); } - Anand Singh
https://dev59.com/CG025IYBdhLWcg3w1ZoL - Ali NajafZadeh
变量 exampleArray = ['myName']; exampleArray.push('hi'); console.log(exampleArray);exampleArray.pop(); console.log(exampleArray); - Ali NajafZadeh
2个回答

164

push()在末尾添加;pop()从末尾删除。

unshift()在前面添加;shift()从前面删除。

splice()可以在任何地方执行任何操作。


146

你其实问了两个问题。根据问题标题,push()的相反操作是pop()

var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);

exampleArray.pop();
console.log(exampleArray);

pop() 方法会从 exampleArray 中移除最后一个元素并返回该元素 ("hi"),但不会删除数组中的字符串 "myName",因为 "myName" 不是最后一个元素。你需要使用 shift()splice() 来实现删除操作。

var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);

exampleArray.shift();
console.log(exampleArray);

var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);

exampleArray.splice(0, 1);
console.log(exampleArray);

更多数组方法请参见:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array#Mutator_methods


1
@jasonscript:记录一下,我从未建议pop()不会从数组中删除最后一个元素。只是它不会删除数组['myName','hi']中的第一个元素myName,这正是@AlexSafayan想要做的。 - Travis Hohl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接