简体   繁体   English

angularjs数组拼接到另一个元素

[英]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. 获得以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. 它只是导致favoriteCourses变量引用同一数组。

$scope.favouriteCourses =  $scope.favouriteCoursesOriginal;

You should use the javascipt slice function to create a copy 您应该使用javascipt slice函数创建副本

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

Please note that slice will only take a shallow copy. 请注意, slice只会进行浅拷贝。 If you require copies of the objects in the array then you need to copy these separately. 如果需要数组中对象的副本,则需要分别复制它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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