【问题标题】:Jquery changing value at original arrayJquery改变原始数组的值
【发布时间】:2019-03-11 03:15:10
【问题描述】:

我制作了一个简单的购物车。

首先,我有一组称为凭证的项目 - 例如:

"[{"id":"108","name":"Gourmet Tasting Menu for Two","price":"85.00","photo":"1102/KtOdtlg.jpg"},{"id":"109","name":"Sampler Menu for Two","price":"60.00","photo":"1102/YrLaHlg.jpg"},{"id":"127","name":"£100 Gift Voucher","price":"100.00","photo":"1102/qexxflg.jpg"}]"

cart = [];

现在我有一个向 CART 数组添加项目的函数:

//with this function based on ID I find object into vouchers array and push that into CART array


    function addItemToCart (id) {
        qty = $('#qty').val();
        var data = $.grep(vouchers, function(e){ return e.id == id; });
        data = data[0];
        data.voucher_id = id;
        data.to = $('#to').val();
        data.from = $('#from').val();
        data.isGift = 0;
        data.recipient_email = $('#recipient_email').val();
        if (data.recipient_email != '') {
            data.isGift = 1;
        }
        data.message = $('#message').val();
        data.qty = qty;
        data.total = qty*data.price;
        cart.push(data);

    };

这很好用,可以将 Item 添加到 CART 中,但也会更改凭证数组中的值。为什么?为什么将data.total 添加到凭证数组中的对象中...

我需要凭证数组具有不可更改的值...为什么当我以这种方式更改值时,它会将值绑定到凭证数组中。

【问题讨论】:

标签: javascript jquery arrays object data-binding


【解决方案1】:

简单地克隆任何类型的数组:

[].concat(data);

由于 concat 在某些 IE 浏览器中可能无法正常工作,您可以使用这个:

new_array = old_array.slice(0);

或者你可以使用

var clonedArray = JSON.parse(JSON.stringify(originalArray))

var clonedArray = $.map(originalArray, function (obj) {
                  return $.extend({}, obj);
              });

【讨论】:

  • 所以我需要更改行 data = data[0];用你的代码?
  • 我得到了 Uncaught TypeError: data.slice is not a function
  • 当您使用在同一数组中搜索的 grep 时,您需要一个深拷贝。由于引用,您正在更改原始值。
  • 但是 GREP 不应该改变原来的数组吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多