如何使用jQuery弹出第一个数组元素?

15

我正在迭代一个 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");
7个回答

40

2

2
如果data.url只是一个数组,解决这个问题的最简单方法是使用JavaScript的splice()函数:
if (data.success) {
  //remove the first element from the urls array
  data.urls.splice(0,1);
  $.each(data.urls, function() {
     ...

如果您需要第一个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() {
     ...

0

你可以使用

.shift()

它将从数组中删除第一个元素

在您的情况下,它是

data.urls.shift()

0
你可以使用数组类的shift()函数,它可以移除(并返回 - 但你也可以直接丢弃)数组中的第一个元素。详细信息请参考MDN文档
data.urls.shift();

0
在JavaScript中,您可以使用shift()来删除数组的第一个元素:
// your array
data.urls;

// remove first element
var firstElem = data.urls.shift();

// do something with the rest

0

在JavaScript中删除数组的第一个元素(如果您使用jQuery也可以)使用data.urls.shift()。这也将返回第一个项目,但是如果您不想使用它,则可以忽略返回值。有关更多信息,请参见http://www.w3schools.com/jsref/jsref_shift.asp


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