添加项目成为对象中的第一个项目

add item to become first item in an object

我要添加 {title:Jessicas',author:'JK', url:"images/beach.jpg"} 成为 book 数组中的第一个对象。

但是当我使用推送信息时,它会成为书中的最后一项。

if ($('#form').valid()){   
     $scope.books.push(
     {
            title: 'Jessicas',
            author: 'JK',
            url: "images/beach.jpg"
     }) 
}

/*  Create JSON representations of the content */ 
$scope.books=[
      {title:'Jani',author:'Norway', url:"images/beach.jpg"},
      {title:'Hege',author:'Sweden',url:"images/plane.jpg"}
];

您可以使用 unshift 方法将元素添加到数组的开头。

Array.prototype.unshift()
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

参考:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift


以类似的方式,或者相反 :) 您可能还想使用与数组检索方法相反的方法。通常你会使用 pop 来获取数组的最后一个元素(即:插入的第一个元素),你可以使用 shift 来访问数组中的最后一个元素(即:最近的已添加)。

您可以使用 unshift 数组方法在数组列表的第一个索引处插入。

$scope.books.unshift({"title:'Whosebug',author:'stack', url:"images/stack.jpg""}) 

这会将对象插入到数组的第一个索引(位置)