【问题标题】:Opposite of push(); [duplicate]与推()相反; [复制]
【发布时间】:2014-10-20 11:25:36
【问题描述】:

我在这个问题上需要帮助 - “JavaScript push(); 方法的对立面是什么?”

就像说我有一个数组 -

var exampleArray = ['remove'];

我想push();这个词'keep' -

exampleArray.push('keep');

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

【问题讨论】:

  • 可以在MDN文档中找到所有数组方法的列表:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 首先,找到要删除的元素的索引:var array = [2, 5, 9]; var index = array.indexOf(5); 注意:浏览器对 indexOf 的支持是有限的; Internet Explorer 7 和 8 不支持它。然后用拼接删除它:if (index > -1) { array.splice(index, 1); }
  • var exampleArray = ['myName']; exampleArray.push('hi');控制台.log(exampleArray); exampleArray.pop(); console.log(exampleArray);

标签: javascript arrays push


【解决方案1】:

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

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

splice() 可以随心所欲。

【讨论】:

    【解决方案2】:

    嗯,你问了两个问题。 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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Mutator_methods

    【讨论】:

    • @jasonscript:为了记录,我从来没有建议pop() 不会从数组中删除最后一个元素。只是它不会删除数组['myName', 'hi'] 中的第一个元素myName,这是@AlexSafayan 想要做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 2011-07-07
    • 2021-12-23
    相关资源
    最近更新 更多