Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

angular - 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);
}
question from:https://stackoverflow.com/questions/65859153/javascript-splice-removes-array-element-at-index-1-instead-of-index

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

splice does not return the updated array.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...