为什么这段代码覆盖我的对象,当我想要它添加到对象

Why does this code overwrite my object when i want it to add to the object

本文关键字:对象 我想要 添加 我的 覆盖 段代码 代码 为什么      更新时间:2023-09-26

我有以下代码。一切都如我所愿,除了一件事。当用户输入另一个item_name(保持room_name不变)时,它会擦除原来的item_name。我需要的是在对象

中添加另一项
<div class="container">
    <div class="row">
        <div class="col-md-4">
             <form>
                <div class="form-group">
                    <input type="text" name="room_name" id="room_name" class="form-control" placeholder="Room name">
                </div>
                <div class="form-group">
                    <input type="text" name="item_name" id="item_name" class="form-control" placeholder="Item name">
                </div>
                <div class="form-group">
                    <input type="text" name="item_description" id="item_description" class="form-control" placeholder="Item description">
                </div>
                <div class="form-group">
                    <input type="text" name="inventory" id="inventory" class="form-control" placeholder="DEBUG">
                </div>
                <div class="form-group">
                    <a id="submitinv" class="btn btn-success btn-block">Submit</a>
                </div>
                <table id="list" class="table table-striped">
                    <tr>
                        <th>ROOM NAME</th>
                        <th>ITEM NAME</th>
                        <th>ITEM DESCRIPTION</th>
                    </tr>
                </table>
             </form>
        </div>
    </div>
</div>
<script>
roominventory = {};
obj = {};
$('#submitinv').click(function(){
    room_name = $('#room_name').val();
    item_name = $('#item_name').val();
    item_description = $('#item_description').val();
    obj[item_name] = item_description;
    roominventory[room_name] = obj;
    $('#inventory').val(JSON.stringify(roominventory));
    obj = {};
    $('#list').append('<tr><td>' + room_name + '</td><td>' + item_name + '</td><td>' + item_description + '</td></tr>');
});
</script>

我们告诉worker:

roominventory[room_name] = obj

我们说的是:

Find the key on the object roominventory that is equivalent to the
value room_name. I now want you to assign the value of obj to that key.

听起来这不是你想告诉你的员工的。听起来你想告诉你的员工的是:

Find the key on the object roominventory that is equivalent to the
value room_name. Now add the object to that value. 
有几种方法可以做到这一点,最简单的是使roominventory对象中的每个键都是一个数组,这样做:
// First we check if we have messed with this key before
if(roominventory[room_name] !== undefined){
  // if we have, let's just push our new object onto the list
  roominventory[room_name].push(obj)
}else{
  // if we haven't, let's create a list of a single item to add to later
  roominventory[room_name] = [obj]
}
相关文章: