switch语句后如何删除数组对象案例

时间:2019-03-18 21:48:38

标签: javascript arrays object if-statement switch-statement

我有一个菜单系统,并且我有一些结帐系统的代码,可以在购物车中显示某些物品时识别交易/折扣。

这是到目前为止的代码:

        var shampoo = false;
        var dye = false;
        var conditioner = false;


            for (var i in cartArray) {
                switch (cartArray[i].name) {
                        case 'Pantene Pro-V':
                        drinks = true;
                        break;
                        case 'Red Dye':
                        chicken = true;
                        break;
                        case 'Herbal Conditioner':
                        kebab = true;
                        break;
                }
                if (shampoo && dye && conditioner) {
                console.log("yes");
                // shoppingCart.removeItemFromCartAll(cartArray[i].name);
                // window.location.reload(true);
                break;
            }
        }
        if (!shampoo || !dye || !conditioner) {
            console.log("no");
        }

控制台日志在完全随机的购物车中显示是,这是肯定的,但是我尝试将这三个项目作为一个组一起删除,但是它不起作用。

这是上面我的删除功能的代码:

      obj.removeItemFromCartAll = function(name) {// removes all item name
        for (var i in cart) {
            if (cart[i].name === name){
                cart.splice(i,1);
                break;
            }
        }
        saveCart();
    };

我尝试插入此代码:

     shoppingCart.removeItemFromCartAll(cartArray[i].name);

在每种情况下,但最终将其逐个移到购物车中,而不是三个一组。

这是控制台的外观(数组对象):

       yes

      (4) [{…}, {…}, {…}, {…}]

       0: {name: "Pantene Pro-V", price: 2.5, count: 1, total: 
       "2.50"}
       1: {name: "Red Dye", price: 4, count: 1, total: "4.00"}
       2: {name: "deodorant", price: 2.5, count: 1, total: "2.50"}
       3: {name: "Herbal Conditioner", price: 1, count: 1, total: "1.00"}
       length: 4
       __proto__: Array(0)

请帮助。谢谢。

最后,我想删除这三个,并从菜单中向购物车中添加另一个项目(例如一个包装,以较低的价格出售这三个...仅供参考)。

编辑-在此处注释此部分

 shoppingCart.removeItemFromCartAll(cartArray[i].name); 

删除购物车中的最后一个项目,并使用拼接方法删除,这会删除整个购物车并破坏购物车系统

3 个答案:

答案 0 :(得分:0)

据我了解,这段代码正确地删除了一个项目

cart.splice(i,1);

这里您提供了1,这意味着它将从作为第一个参数提供的索引中删除1个项目。尝试将其更改为3。

更糟糕的情况是,如果您有隆隆的数组,而这3个项目彼此都不是。然后充其量您应该创建一些属性,该属性可以将项目分配给特定的组,然后使用数组的filter方法过滤出要删除的组中的项目

答案 1 :(得分:0)

使用删除关键字

obj.removeItemFromCartAll = function(name) {// removes all item name
        for (var item in cart) {
            if (cart[item].name === name){
                delete cart[item]
                break;
            }
        }
        saveCart();
    };

答案 2 :(得分:0)

  

“在每种情况下,最终都将其逐个移到购物车中,而不是三个一组。”

由三个或三个单独的项目组成的组并不重要,重要的是将它们删除。应该考虑这样的情况,例如客户的销售商品少于3个,或者根本没有和/或订购顺序不同。充当过滤器的开关是个坏主意,您要避免对动态数据进行硬编码(我假设购物车中的商品对于每个客户而言都是不同的,并且销售商品最终也会更改。)

演示大纲

  1. 列表:代表客户购物车内容的对象数组。
  2. 销售:代表当前正在销售的商品的对象数组。
  3. 将两个数组都转换为Maps。
    var discount = convertToMap(list, "name")
    var customer = convertToMap(sale, "name")
    
  4. 比较折扣客户相互映射,并将每个匹配的键/值对从折扣合并到客户
  5. 结果是具有以下模式的地图:
     `[["Muffin Mix - Raisin Bran", {"name":"Muffin Mix - Raisin Bran","price":5.85,"qty":1,"total":2.92,"saved":2.93}], ...]`
    

演示

// Sale Items - Note the "total" and "saved" values
let sale = [
{"name":"Flavoring - Orange","price":4.57,"qty":1,"total":2.00,"saved":2.57},
{"name":"Muffin Mix - Raisin Bran","price":5.85,"qty":1,"total":2.92,"saved":2.93},
{"name":"Pepsi - Diet, 355 Ml","price":3.63,"qty":1,"total":1.81,"saved":1.82}
]; 

// Cart Items - This represents the customer's cart
let cart = [
{"name":"Plastic Arrow Stir Stick","price":0.75,"qty":1,"total":0.75,"saved":0},
{"name":"Veal - Round, Eye Of","price":22.91,"qty":1,"total":22.91,"saved":0},
{"name":"Calypso - Pineapple Passion","price":8.69,"qty":1,"total":8.69,"saved":0},
{"name":"Sloe Gin - Mcguinness","price":33.27,"qty":1,"total":33.27,"saved":0},{"name":"Wine - Sake","price":28.47,"qty":1,"total":28.47,"saved":0},
{"name":"Dried Figs","price":1.78,"qty":1,"total":1.78,"saved":0},
{"name":"Pepsi - Diet, 355 Ml","price":3.63,"qty":1,"total":3.63,"saved":0},
{"name":"Olives - Moroccan Dried","price":15.17,"qty":1,"total":15.17,"saved":0},
{"name":"Muffin Mix - Raisin Bran","price":5.85,"qty":1,"total":5.85,"saved":0}
];

/*
@ convertToMap(array, key) 
@ Params: array [Array of Objects]..(ex. list)
@         key [String]..............(ex. "name")
@ Converts an Array of Objects to a MAP
@ iNPUT: [{key,...}, {key,...}, {key,...}], key
@ ~~~~~~~~~~~~~~===~~~~~~~~~~~~~~~
@ OUTPUT: [[key, {key,...}], [key, {key,...}], [key, {key,...}]]
*/
const convertToMap = (array, key) => {return new Map(array.map(item => [item[key], item]));};

// Get a Map of sale
const discount = convertToMap(sale, 'name');
// Get a Map of cart
const customer = convertToMap(cart, 'name');

/*
@ mergeMaps(mapA, mapB)
@ Params: mapA [Map]...smaller Map...(ex. [[...], [...]])
@         mapB [Map]...larger Map....(ex. [[...], [...]])
@ Compares MapA to MapB
@ If any matches by value occur, 
@ replace MapB key/value with MapA key/value
*/
const mergeMaps = (mapA, mapB) => {
  for (let key of mapB.keys()) {
    if (mapA.has(key)) {
      mapB.set(key, mapA.get(key));
    }
  }
  return mapB;
};

let shoppingA = mergeMaps(discount, customer);

console.log(shoppingA.get("Sloe Gin - Mcguinness"));
console.log("~~~~~~~~~~~~~~~~~~~~~-====-~~~~~~~~~~~~~~~~~~~~~");

// [OPTION] Convert new Map to a 2D Array 
let shoppingB = Array.from(mergeMaps(discount, customer));

console.log(shoppingB);