声明它的变量未定义的外部函数

时间:2017-09-18 02:12:39

标签: javascript

第一个函数中显示的变量和值已显示在第二个函数中,但不显示

按照代码:JavaScript

//This function display
function addProduct(){

    var productList = [];
    var product1;
    var product2;
    var allProductList;

    productList = [];
    product1 = document.getElementById('product1').value;
    product2 = document.getElementById('product2').value;
    productList.push(product1,product2);
    allProductList = productList;
    alert(allProductList);
}

//This function does not display
function showList(){
    alert(allProductList);
}

按照标记:HTML

<button onclick="addProduct();">Adicionar</button>

<button onclick="showList();">Exibir</button>

2 个答案:

答案 0 :(得分:0)

您必须在全局范围内声明allProductList

现在它在第一个函数addProduct()中声明,因此在showList()方法中不可见。

因此你应该像这样声明变量:

//declare such that it is visible to both the methods
var allProductList = [];
var productList = [];

function addProduct(){

    var product1;
    var product2;
    product1 = document.getElementById('product1').value;
    product2 = document.getElementById('product2').value;
    productList.push(product1,product2);
    allProductList = productList;
    alert(allProductList);
}

//This function does not display
function showList(){
    alert(allProductList);
}

答案 1 :(得分:0)

如果函数被设计为产生某个值,那么使用函数返回该值。这是一个更好的设计,而不是让函数将其结果放在一个神奇的全局变量中,你可能会忘记,或者无法正确声明(正如你所做的那样)。

// Retrieve the products, and return a product list.
function addProduct(){
    var productList = [];
    var product1;
    var product2;

    product1 = document.getElementById('product1').value;
    product2 = document.getElementById('product2').value;
    productList.push(product1,product2);

    alert(productList);

    // Return the result as the function's value.
    // It may be accessed as addProduct().
    return productList;
 // ^^^^^^^^^^^^^^^^^^^
}

// Display the calculated product list.
function showList(){
    alert(addProduct());
 //       ^^^^^^^^^^^^
}
相关问题