【问题标题】:How to display all object in array from local storage jquery如何从本地存储jquery显示数组中的所有对象
【发布时间】:2021-10-26 03:40:27
【问题描述】:

我制作了一个包含购物车项目数据的对象数组,现在添加项目后,我想显示购物车中项目的所有数据。 如何显示? 我不知道如何访问对象中的属性和数组中的对象

var cartArray = []; //array of cart Items data
    var total = 0;
    var shipping = 2;

    $(".addToCart").click(function(){

               var flag = 0;
        //Get all data of item to be added
            var id= $(this).data("id");
            var price= $(this).data("price");
            var image = $(this).data('image');
            var name = $(this).data("name");
            var quantity = $(this).data("quantity");
            var availability = $(this).data("availability");
            var weight = $(this).data("weight");


            //check if cart is empty to remove empty cart view
               if( (cartArray.length === 0) ) { 
                $("#empty-cart").css("display","none");}

            //Traverse the cart list to check if item already exists or not
                 $.map(cartArray,function(item){
                 if (item.I == id){
                  item.Q++;
                  flag = 1;
                  console.log("each function runned,quantity increased");
                  console.log(item.Q);
                    return false;
                   }
                 })

          //Add new Item in cart
              if(flag == 0){
                  var itemObj ={
                    I : id,
                    IMG : image,
                    N : name,
                    W : weight,
                    A : availability,
                    P : price,
                    Q : quantity,
                  }
                     cartArray.push(itemObj);
                     localStorage.setItem('cartItem',JSON.stringify(cartArray)); 

                  var getItems = JSON.parse(localStorage.getItem('cartItem'));  
});


【问题讨论】:

  • 从本地存储中发布您的示例 json

标签: javascript jquery arrays object cart


【解决方案1】:

这里是一个如何从数组和对象中获取值的示例。

您还可以在此 url 中看到数组的工作原理: https://www.cpp.edu/~elab/ECE114/Array.html

let getItems = [2, 3, 7, {"key": "value"}];

//first value is array
getItems[0];
console.log(getItems[0]);

//second value is array
getItems[1];
console.log(getItems[1]);

//third value is array
getItems[2];
console.log(getItems[2]);

//fourth value which is object
getItems[3].key;
console.log(getItems[3].key);

【讨论】:

    猜你喜欢
    • 2019-05-16
    • 2018-11-04
    • 1970-01-01
    • 2021-09-22
    • 2013-04-16
    • 2015-07-02
    • 2019-10-27
    • 2023-03-14
    • 2013-09-22
    相关资源
    最近更新 更多