首页 > 解决方案 > JavaScript Array.length 在函数中为 2,但在另一个函数中为 0

问题描述

我正在尝试用东西填充表格,但是当我在浏览器上运行时,没有显示数据。我尝试在开发控制台中输出 stuff 数组的长度,首先它显示正确的值,但是当我调用函数来填充表格时,数组的内容消失了。

这是代码:

const PRODUCT_CART_URL = "https://japdevdep.github.io/ecommerce-api/cart/654.json";
var cpArray = [];

var getJSONData = function(url){
    var result = {};
    return fetch(url)
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw Error(response.statusText);
            }
        })
        .then(function(response) {
            result.status = 'ok';
            result.data = response;
            return result;
        })
        .catch(function(error) {
            result.status = 'error';
            result.data = error;
            return result;
        });
}

function fetchCartProducts() {
    getJSONData(PRODUCT_CART_URL).then(function(resultObj) {
        if (resultObj.status === "ok") {
            cpArray = resultObj.data.articles;
            console.log(cpAray.length); // It's 2 as it sould be
        }
    });
}

function showCartProducts() {
    let newHTML = "";
    let pTable = document.getElementById("products_table");
    console.log(cpArray); // It's 0, how???
    for (let i = 0; i < cpArray.length; i++) {
        console.log("Iteración 1");
        newHTML += `<tr>
                                <td data-th="Product">
                                    <div class="row">
                                        <div class="col-sm-2 hidden-xs"><img class="prod-img" src="` + cpArray[i].src + `" alt="Foto del producto" class="img-responsive"/></div>
                                        <div class="col-sm-10">
                                            <h4 class="nomargin">` + cpArray[i].name + `</h4>
                                            <p>Descripción del producto</p>
                                        </div>
                                    </div>
                                </td>
                                <td data-th="Precio: ">` + cpArray[i].currency + " " + cpArray[i].unitCost`</td>
                                <td data-th="Quantity">
                                    <input type="number" class="form-control text-center" value="1">
                                </td>
                                <td data-th="Subtotal" class="text-center">1.99</td>
                                <td class="actions" data-th="">
                                    <button class="btn btn-info btn-sm"><i class="fa fa-refresh"></i></button>
                                    <button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>                                
                                </td>
                            </tr>`;
    }
    
    pTable.innerHTML = newHTML;
}

document.addEventListener("DOMContentLoaded", function() {
    fetchCartProducts();
    showCartProducts();
}); 

这怎么可能?我找不到我的代码错误的地方。

标签: javascriptarrays

解决方案


推荐阅读