gpt4 book ai didi

Javascript 访问私有(private)数组

转载 作者:行者123 更新时间:2023-12-03 08:21:38 24 4
gpt4 key购买 nike

我需要做到这一点,以便每次您单击一包口香糖的图片时,它都会根据单击的口香糖图片将总价格加在一起。它还必须计算点击图片的次数以显示购物车商品数量。我必须有一个私有(private)数组。但我似乎不知道如何调用它,这样我就可以获得被点击的口香糖的价格

var addPrice = function(gum) {

total = 0;
if (gum == extra) {
total += brands.price[0];
}
if (gum == twoMint) {
total += brands.price[1];
}
if (gum == trident) {
total += brands.price[2];
}
if (gum == bubble) {
total += brands.price[3];
}
document.getElementById("totalAmount").innerHTML = total;
};

var clear = function() {
};

var createArray = function() {

var gumArray = function() {

var brands = [{
brand: "extra",
price: 1.50
}, {
brand: "twoMint",
price: 0.25
}, {
brand: "trident",
price: 2.50
}, {
brand: "bubble",
price: 0.10
}]
};
};

document.getElementById("extra").addEventListener("click", function() {
addPrice("extra"); -
console.log("gum clicked");
});

document.getElementById("twoMint").addEventListener("click", function() {
addPrice("twoMint");
console.log("gum clicked");
});

document.getElementById("trident").addEventListener("click", function() {
addPrice("trident");
console.log("gum clicked");
});

document.getElementById("bubble").addEventListener("click", function() {
addPrice("bubble");
console.log("gum clicked");
};

最佳答案

如果您的目的是为此代码创建一个模块,让我向您展示一个模块的示例,很难说只有一件事可以将您的代码变成模块。

您需要一个返回一个对象的函数,该对象可以访问所创建的闭包中的变量。这些变量对外部不可见,除非您将其公开为模块的一部分。

var cart = (function() {
// These vars are private, not directly accessible from the outside
var total = 0;
// Map for faster access
var brands = {extra: 1.50, twoMint: 0.25, trident: 2.50, bubble: 0.10};
// Private function
function updateUI() {
document.getElementById("totalAmount").innerHTML = total;
}

// The exported module
return {
addPrice: function(gum) {
total += brands[gum];
updateUI();
},
// The outside can get the value of total, but they can't change it directly
getTotal: function() {
return total;
},

clear: function() {
total = 0;
updateUI();
}

};
})();

["extra", "twoMint", "trident", "bubble"].forEach(function(id){
document.getElementById(id).addEventListener("click", function() {
cart.addPrice(id);
});
});

关于Javascript 访问私有(private)数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com