简体   繁体   中英

angularjs array splice to another element

My aim is to create a carousel like function that will rotate the list of favourite courses. On the code, i assigned the array to another scope and spliced it for first view. It works fine. While splicing the new array the old array is also spliced. The output is mentioned along with the code. Why the original array is also changing.

What is the best logic to get a circular list of courses displayed in multiples of 3.

 $scope.favouriteCoursesOriginal = [

    {title:'courseA', stars:5, image:'image.png'},
    {title:'courseB', stars:5, image:'image.png'},
    {title:'courseC', stars:5, image:'image.png'},
    {title:'courseD', stars:5, image:'image.png'},
    {title:'courseE', stars:5, image:'image.png'},
    {title:'courseF', stars:5, image:'image.png'},
    {title:'courseG', stars:5, image:'image.png'},
    {title:'courseH', stars:5, image:'image.png'},
    {title:'courseI', stars:5, image:'image.png'}
];

     console.log($scope.favouriteCoursesOriginal.length); //Output = 9;
    $scope.favouriteCourses =  $scope.favouriteCoursesOriginal;
    $scope.favouriteCourses.splice(0,3);
    console.log($scope.favouriteCoursesOriginal.length); //Output = 6;

The following line of code does not make a copy by value of the original array. It simply results in the favoriteCourses variable referring to the same array.

$scope.favouriteCourses =  $scope.favouriteCoursesOriginal;

You should use the javascipt slice function to create a copy

$scope.favouriteCourses =  $scope.favouriteCoursesOriginal.slice();

Please note that slice will only take a shallow copy. If you require copies of the objects in the array then you need to copy these separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM