Javascript 添加或拼接数组的函数

Javascript function to add to or splice array

我有两个按钮,每个按钮添加一个数组到数组orderArray。这工作正常,数组显示为 html table。当输出 table 时,还会创建一个按钮。此按钮的目的是删除与其关联的数组,从而从 table 中删除一行。

这很好用,但是在用 .splice 删除数组的一部分之后就不可能再向数组中添加更多内容,它只会抛出 "cannot read property length".

在控制台可以看到数组已经拼接好,长度值是正确的,但是还是报错。我显然在这里没有得到任何东西,因为我认为当循环调用 myArray.length 时它每次都会得到正确的长度。

这是js:

var orderArray = [];
var orderNumber = 0;
var theOrder = [];
var total = 0;

function orderUpdate(item,price){
    theOrder = [item, price];
    orderArray[orderNumber] = theOrder;
    orderNumber++;
}

function makeTable(myArray) {
    var result = "<table border=2 id=orderTable>";
    console.log(myArray.length);
    for(var i = 0; i < myArray.length; i++) {
        result += "<tr id='row" + i + "'>";
        for(var j = 0; j < myArray[i].length; j++){
            result += "<td>" + myArray[i][j] + "</td>";

        }
        result += "<td><button onclick='removeLine(" + i + ")'>Remove</button></td></tr>";
    }
    result += "</table>";
    console.log(myArray);
    return result;
}

$( "#LongB" ).click(function() {
    orderUpdate("Long Black", 2.50);
    $("#ordered").html(makeTable(orderArray));
});

$( "#FlatW" ).click(function() {
    orderUpdate("Flat White", 3.50);
    $("#ordered").html(makeTable(orderArray));
});

function removeLine(arrayIndex){
    orderArray.splice(arrayIndex, 1);
    console.log(orderArray);
    $("#ordered").html(makeTable(orderArray));
}

和 html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSPOS</title>
    <script src="http://code.jquery.com/jquery-2.1.4.js"></script>

</head>
<body>

<button id="LongB">Long Black</button>
<button id="FlatW">Flat White</button>
<h3>Ordered:</h3>
<div id="ordered"></div>

<script src="js/stuff.js"></script>
</body>
</html>

here 它是作为 fiddle.

这是因为您在添加新项目时增加了 orderNumber,但是当您删除项目时忘记减少 orderNumber,所以您得到了错误,因为索引不存在于数组:-

function removeLine(arrayIndex){
orderArray.splice(arrayIndex, 1);
console.log(orderArray);
 orderNumber--; //add this line
$("#ordered").html(makeTable(orderArray));
}

Demo

尝试用 orderArray.push(theOrder); 代替 orderArray[orderNumber] = theOrder;

function orderUpdate(item,price){
    theOrder = [item, price];
    orderArray.push(theOrder);
    // orderNumber++;
}

jsfiddle https://jsfiddle.net/purnrntr/2/