简体   繁体   English

javascript变量返回未定义状态

[英]javascript variables returning as undefined

I am working with some javscript at the moment, the basic thought process behind it is that, you click a link and that links produces and entry in a basket, I currently logged what gets sent to the basket in my console. 目前,我正在处理一些脚本,其背后的基本思想过程是,单击一个链接,该链接会在篮子中生成和输入,我目前在控制台中记录了发送到篮子的内容。 When I click a link it triggers the additem() function, 当我单击链接时,它会触发additem()函数,

function additem(desc,price,quantity)
    {

        var x = items.length - 1;
        var found = (x == 0);
        var y = new Item(desc,price,parseInt(quantity));
        console.log(y);
        var z = y;

        while((x != 0) && (found == false))
        {
            z = items[x];

            if(z != null)
            {
                if(z.M_desc == desc)
                {
                    found = true;
                }
                else
                {
                    x--;
                }
            }
            else
            {
                x--;
            }
        }

        if(found == false)
        {
            items[++numitems] = y;
        }
        else
        {
            items[x].M_quantity += quantity;
        }

        updatecart();
    }

What I see in the console is the following, 我在控制台中看到的是以下内容,

Item { M_desc="Item 2", M_price="10", M_quantity=1}

however when I click into it, I get the following , 但是,当我单击它时,我得到以下信息,

M_desc
    "Item 2"

M_price
    "10"

M_quantity
    undefined

How can M_quantity be 1 and then undefined in another console view? M_quantity如何设为1,然后在另一个控制台视图中未定义?

===== EDIT ===== =====编辑=====

I think the problem stems form here, my JS code starts with the line. 我认为问题出在这里,我的JS代码从这一行开始。

var items = new Array(2);

now I assume that this creates a new array as when I run console.log(items) straight after it I get [undefined, undefined] . 现在,我假设这会在我获得[undefined, undefined]之后立即运行console.log(items)时创建一个新数组。

additem is called on the click of a link using the following code, 单击链接使用以下代码调用additem,

HTML 的HTML

<a class='product' rel='"+category[i].product[j].price+"' href=''>"+ category[i].product[j].description + "</a>

JS JS

$('.product').live("click",function(e){
    additem($(this).text(), $(this).attr('rel'), 1);
e.preventDefault();
});

This is when the problems arise as items[x] is either always null or undefined. items[x]始终为null或未定义时,就会出现问题。 and I not sure why. 我不知道为什么。

Your updatecart function is being called almost simultaneously. 您的updatecart函数几乎同时被调用。 items[i].M_quantity = $('input[name="qty"]').val() is the problematic line. items[i].M_quantity = $('input[name="qty"]').val()是有问题的行。 The input is null and is replacing your quantity with undefined. 输入为空,正在用undefined替换您的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM