JavaScript中push();
方法的相反方法是什么?
假设我有一个数组:
var exampleArray = ['remove'];
我想要 push();
单词 'keep'
-
exampleArray.push('keep');
我如何从数组中删除字符串'remove'
?
JavaScript中push();
方法的相反方法是什么?
假设我有一个数组:
var exampleArray = ['remove'];
我想要 push();
单词 'keep'
-
exampleArray.push('keep');
我如何从数组中删除字符串'remove'
?
push()
在末尾添加;pop()
从末尾删除。
unshift()
在前面添加;shift()
从前面删除。
splice()
可以在任何地方执行任何操作。
你其实问了两个问题。根据问题标题,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);
pop()
不会从数组中删除最后一个元素。只是它不会删除数组['myName','hi']
中的第一个元素myName
,这正是@AlexSafayan想要做的。 - Travis Hohl
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