为什么splice()数组方法总是删除Javascript中所选索引后面的所有对象



我目前正在学习Javascript,老师要求我们创建一个程序,允许用户使用对象数组创建、编辑和删除酒店。

我成功地创建了showHotels()函数,没有任何问题,但我在从创建的数组中删除特定的酒店时遇到了问题,因为当我使用splice()方法时,它会删除所选的对象,但也会删除以下所有对象。

用户必须输入酒店名称才能将其删除,因此我们不知道对象的索引。

我只被允许使用Visual Studio代码,而不允许使用其他代码来编写代码。


import { Hotel } from "./hotels.js"
document.getElementById('createHotel').addEventListener('click', createHotel)
document.getElementById('deleteHotel').addEventListener('click', deleteHotel)
document.getElementById('showHotel').addEventListener('click', showHotel)
document.getElementById('editHotel').addEventListener('click', editHotel)
let myHotelArray = []
function createHotel() {
const hotelName = prompt(`Please enter the name of hotel:`, `W Hotel`)
const numberOfRooms = prompt(`Please enter the number of rooms:`, `68`)
const numberOfFloors = prompt(`Please enter the number of floors:`, `12`)
const totalArea = prompt('Please enter the total area of the hotel:', `250`)
myHotelArray.push(new Hotel(hotelName, numberOfRooms, numberOfFloors, totalArea))
}

function showHotel() {
let hotelsFormated = []
for (let i = 0; i < myHotelArray.length; i++) {
hotelsFormated.push(`${myHotelArray[i].toString()} <br><br>`);
}
document.getElementById('hotels').innerHTML = hotelsFormated.join('')
console.log(myHotelArray)
}

function deleteHotel() {
const selectHotel = prompt(`Please enter the name of the hotel you'd like to delete:`)
const hotelIndex = myHotelArray.findIndex(i => i.hotelName === selectHotel)
if (hotelIndex >= 0) {
myHotelArray.splice(hotelIndex)
}
else {
alert("This hotel couldn't be found. Please try again")
}
function editHotel() {
}
}

如mdn Array.splice中所述,它可以接收两个参数:

  1. start:从零开始更改数组的索引(不要知道从零开始的意思,但使用任意起始参数自然数)

  2. deleteCount:一个整数,表示要从一开始删除的数组。

我认为像myHotelArray.splice(hotelIndex, 1)这样在您的报表中添加deleteCount会解决问题。

splice方法将从列表中删除,并将所有项目从hotelIndex返回到hotelIndex+deletCount。

最新更新