将值从对象数组发送到 JavaScript 中的函数

Sending values from an array of object to a function in JavaScript

我正在尝试将数组内对象(称为 id)的属性值发送到函数,该函数将删除数组内的该对象。按钮由 innerHTML 创建,根据数组有多少个值,它创建一个按钮,每个按钮删除其在数组中的对应对象。我有这个代码:

<script>
var ingredientsArray = [];
var contid = 0;

function ingredients(id, name, status) {
    this.id = id;
    this.name = name;
    this.status = status;
}

document.querySelector("#button").addEventListener('click', function () {

    var x = document.getElementById("List").value;
    var objectIngredient = new ingredients(contid, x, false);
    ingredientsArray.push(objectIngredient);
    localStorage.setItem('ingredientsArray', JSON.stringify(ingredientsArray));
    console.log(ingredientsArray);
    contid++;
    draw()
});

function draw() {
    document.querySelector('#list').innerHTML = '';
    document.querySelector('#list').innerHTML = '<ul>';
    for (var i = 0; i < ingredientsArray.length; i++) {
        var x = '';
        var clas = '';
        if (x == true) {
            x = 'checked="cheked"';
            clas = 'strike()'
        }
        document.querySelector('#list').innerHTML += '<li>' + ingredientsArray[i].name;
        document.querySelector('#list').innerHTML += '<input type="checkbox" + x>';
        document.querySelector('#list').innerHTML += '<button onclick="erase(i)">erase</button>';
        console.log(ingredientsArray[i].id);
        document.querySelector('#list').innerHTML += '</li>';
    }
    document.querySelector('#list').innerHTML += '</ul>';
}

function erase(i) {
    var index = ingredientsArray.indexOf(i);
    ingredientsArray.splice(index, 1);
}

但是当按下按钮时,控制台显示函数期望的值为空。有谁知道为什么?谢谢!

看来您只需稍微修改一下代码即可使其正常工作,我会试试这个:

<button onclick="erase(' + i + ')">erase</button>

...

function erase(index) {
    ingredientsArray.splice(index, 1);
}