javascript 如何使用 jquery 弹出第一个数组元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13274166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I pop off the first array element with jquery?
提问by Paul
I'm iterating through an array of json data but need to remove the first element prior to the iteration. How do I remove the initial element? This is what I have so far:
我正在遍历一组 json 数据,但需要在迭代之前删除第一个元素。如何删除初始元素?这是我到目前为止:
$.post('player_data.php', {method: 'getplayers', params: $('#players_search_form').serialize()}, function(data) {
if (data.success) {
// How do I remove the first element ?
$.each(data.urls, function() {
...
});
}
}, "json");
回答by Adriano Carneiro
Plain javascript will do:
普通的 javascript 会做:
data.urls.shift()
On shift()
method:
方法论shift()
:
Removes the first element from an array and returns that element. This method changes the length of the array.
从数组中删除第一个元素并返回该元素。此方法更改数组的长度。
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/shift
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/shift
回答by AlexStack
If data.url
is just an array, the simplest way to solve this problem is to use the Javascript's splice()function:
如果data.url
只是一个数组,解决这个问题最简单的方法是使用Javascript的splice()函数:
if (data.success) {
//remove the first element from the urls array
data.urls.splice(0,1);
$.each(data.urls, function() {
...
You can also use shift()if you need the value of the first url:
如果需要第一个 url 的值,也可以使用shift():
if (data.success) {
//remove the first element from the urls array
var firstUrl = data.urls.shift();
//use the value of firstUrl
...
$.each(data.urls, function() {
...
回答by Juan Mendes
There's a method like pop, but from the front instead
有一个类似 pop 的方法,但是从前面代替
data.urls.shift()
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/shift
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/shift
回答by Sushanth --
You can use
您可以使用
.shift()
It will remove the first element from the array
它将从数组中删除第一个元素
In your case it is
在你的情况下是
data.urls.shift()
回答by Anthony Grist
回答by Sirko
回答by Joshua Dwire
To remove the first item of an array in javascript (it will also work if you're using jquery) use data.urls.shift()
. This will also return the first item, but you can ignore the return value if you don't want to use it. For more info, see http://www.w3schools.com/jsref/jsref_shift.asp.
要在 javascript 中删除数组的第一项(如果您使用 jquery,它也可以工作)使用data.urls.shift()
. 这也将返回第一项,但如果您不想使用它,您可以忽略返回值。有关详细信息,请参阅http://www.w3schools.com/jsref/jsref_shift.asp。