【问题标题】:Javascript function to add to or splice array添加或拼接数组的 Javascript 函数
【发布时间】:2015-10-03 13:19:06
【问题描述】:

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

这很好用,但是在使用 .splice 删除部分数组后,无法再向数组添加更多内容,它只会抛出“无法读取属性长度”。

在控制台可以看到数组拼接完成,长度值正确但错误依旧。我显然在这里没有得到任何东西,因为我认为循环调用 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 就像小提琴一样。

【问题讨论】:

    标签: javascript jquery arrays splice


    【解决方案1】:

    这是因为您在添加新项目时增加了orderNumber,但是当您删除项目时却忘记减少orderNumber,因此出现错误,因为数组中不存在索引:-

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

    Demo

    【讨论】:

    • 你以 32 秒的优势击败了我,这让我投了 2 票。太好了。
    • 另外,您可以使用push 添加和splice 删除(您已经这样做了)并让JS 进行计数。使用orderArray.push(theOrder); 就足够了。
    • 好吧,我只是解释一下他为什么会出现这个错误,否则有很多更好的方法可以实现相同的功能
    【解决方案2】:

    尝试将orderArray.push(theOrder); 替换为orderArray[orderNumber] = theOrder;

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

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

    【讨论】:

      猜你喜欢
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 2021-03-19
      • 2015-02-22
      • 2019-10-16
      • 1970-01-01
      相关资源
      最近更新 更多