You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中splice()方法为何删除选中索引后的所有对象?酒店数组删除异常

解决JavaScript中使用splice删除指定酒店时误删后续元素的问题

问题原因

你遇到的核心问题是**splice()方法的参数使用错误**:当你只传入起始索引hotelIndex时,splice()会默认删除从该索引位置开始到数组末尾的所有元素。正确的用法需要传入第二个参数,指定要删除的元素数量。

修正后的代码

首先修正deleteHotel函数的splice调用,同时注意你的editHotel函数嵌套在deleteHotel内部,这会导致点击编辑按钮时无法触发该函数,需要将其移到外部:

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(hotel => hotel.hotelName === selectHotel)

    if (hotelIndex >= 0) {
        // 传入第二个参数1,仅删除指定索引的单个元素
        myHotelArray.splice(hotelIndex, 1)
        // 可选:删除后实时更新页面显示
        showHotel()
    } else {
        alert("This hotel couldn't be found. Please try again")
    }
}

// 将editHotel移到deleteHotel外部,确保点击编辑按钮能触发函数
function editHotel() {
    // 补充编辑逻辑示例
    const hotelName = prompt(`Enter the name of the hotel to edit:`)
    const targetHotel = myHotelArray.find(hotel => hotel.hotelName === hotelName)
    if (targetHotel) {
        targetHotel.numberOfRooms = prompt(`Enter new number of rooms:`, targetHotel.numberOfRooms)
        targetHotel.numberOfFloors = prompt(`Enter new number of floors:`, targetHotel.numberOfFloors)
        targetHotel.totalArea = prompt(`Enter new total area:`, targetHotel.totalArea)
        showHotel()
    } else {
        alert("Hotel not found")
    }
}

额外优化建议

  1. 处理同名酒店的情况:如果数组中存在多个同名酒店,findIndex只会找到第一个匹配项。如果你想删除所有同名酒店,可以使用filter方法:
function deleteHotel() {
    const selectHotel = prompt(`Please enter the name of the hotel you'd like to delete:`)
    const originalLength = myHotelArray.length
    myHotelArray = myHotelArray.filter(hotel => hotel.hotelName !== selectHotel)
    if (myHotelArray.length === originalLength) {
        alert("This hotel couldn't be found. Please try again")
    } else {
        showHotel()
    }
}
  1. 输入验证:在createHotel中添加输入合法性验证,比如判断房间数、楼层数是否为正整数,避免无效数据存入数组。
  2. 实时反馈:删除或编辑操作完成后自动调用showHotel(),让页面实时更新,无需用户手动点击显示按钮。

内容的提问来源于stack exchange,提问作者kecaey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 09:25:26