简体   繁体   English

为什么我的对象没有被推入不同的数组?

[英]Why is my object not being pushed into a different array?

I had the objects being pushed from the storeItems array, into the cartItems array and printing in the div successfully, but after adding more functionality it no longer adds to the array (checked via the console and there is a length value of 0).我将对象从 storeItems 数组推送到了 cartItems 数组并成功打印在 div 中,但在添加更多功能后,它不再添加到数组中(通过控制台检查,长度值为 0)。 What am I not seeing??我没看到什么??

I just need to transfer the user selected object from the storeItems array into the cart Items then it will print successfully我只需要将用户选择的对象从 storeItems 数组转移到购物车 Items 中,然后它就会成功打印

//Function to add an item to users cart & update total
function addItem() {
  var addId = document.getElementById("addItemId").value;
  var itemQty = document.getElementById("addItemQty").value;

  for (x = 0; x < storeItems.length; x++) {
    //Calling validation functions
    validateId();
    validateQty();


    if (addId === storeItems[x].id) {
      cartItems.push(new CartItem(storeItems[x].id, storeItems[x].name, storeItems[x].price, storeItems[x].qty, storeItems[x].shippingCost));
      displayCart();
    }

  }

  console.log(cartItems);
}

I just need to transfer the user selected object from the storeItems array into the cart Items then it will print successfully我只需要将用户选择的对象从 storeItems 数组转移到购物车 Items 中,然后它就会成功打印

Okay, here i go, I did some changes in your code, to make it workable for me.好的,我走了,我对您的代码进行了一些更改,以使其对我有用。

have a look to my code看看我的代码

var storeItems = [1,2,3,4,5,6]

function addItem(addId, itemQty) {
function addItem(addId, itemQty) {
  for (x = 0; x < storeItems.length; x++) {
    //Calling validation functions
    if (addId === storeItems[x]) {
      cartItems.push(x);
    }
  }
  console.log(cartItems);
}

addItem(6);

According to my deduction, dear Watson, in your code following if condition is not working根据我的推论,亲爱的沃森,在你的代码中,如果条件不起作用

 if (addId === storeItems[x].id) {
     ....
    }

debug this condition.调试这个条件。 this may help you !这可能会帮助你!

Be sure that you are using the correct comparison operator when comparing against a value and a text input.在与值和文本输入进行比较时,请确保使用正确的比较运算符。 The text input will come back as a string no matter what the type="" value is set to.无论type=""值设置为什么,文本输入都将作为字符串返回。

So when comparing an input to actual data do one of the following:因此,在将输入与实际数据进行比较时,请执行以下操作之一:

  • Use == instead of === to ignore/skip type comparisons使用==而不是===忽略/跳过类型比较
  • Cast the input value to the type that it should be then you can use ===将输入值转换为它应该是的类型,然后您可以使用===
    • parseInt(myInput) === myNonInput
    • new Date(myInput).getTime() === myNonInput.getTime()
    • myInput === myNonInput.toString()
    • etc.等等。

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

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