简体   繁体   中英

JavaScript splice removes array element at index + 1 instead of index

I'm seeing a weird issue where splice appears to remove an element at the index + 1 instead of the correct index. For instance, if selectedCourseMediaIndex = 0, then the element at index 1 in the array is removed. Is there any particular reason why this is happening?

  courseMedia: [
    {
      name: 'testing_startup_ideas.mp3',
      url:
        'https://s3.eu-west-2.amazonaws.com/media.test.co.uk/default/testing_startup_ideas.mp3',
      type: CourseContentMediaType.AUDIO,
    },
    {
      name: 'biggest_mistake_founders_make.mp3',
      url:
        'https://s3.eu-west-2.amazonaws.com/media.test.co.uk/default/biggest_mistake_founders_make.mp3',
      type: CourseContentMediaType.AUDIO,
    },
  ],

onEditAudioItemDeleteButtonClick() {
  let courseMedia = JSON.parse(JSON.stringify(this.courseMedia));
  courseMedia = CourseContentService.deleteCourseMediaByIndex(
    courseMedia,
    this.selectedCourseMediaIndex
  );
}

static deleteCourseMediaByIndex(
  courseMedia: ICourseMedia[],
  selectedCourseMediaIndex: number
): ICourseMedia[] {
  return courseMedia.splice(selectedCourseMediaIndex, 1);
}

splice does not return the updated array.

static deleteCourseMediaByIndex(
  courseMedia: ICourseMedia[],
  selectedCourseMediaIndex: number
): ICourseMedia[] {
  courseMedia.splice(selectedCourseMediaIndex, 1);
  return courseMedia
}

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