Javascript JS Split()检查数组中是否存在子字符串
我有一个产品的Javascript JS Split()检查数组中是否存在子字符串,javascript,jquery,arrays,split,Javascript,Jquery,Arrays,Split,我有一个产品的数组,这些产品存储为字符串,格式为productname:quantity。我遇到的问题是,如果用户添加了一个数量为x的产品,它会按其应该的方式插入到数组中。但是,如果他们随后决定添加更多特定产品,则会在数组中创建一个新条目,而不是检查该产品是否已存在并将数量调整为新值旧数量+新数量 例如,这是我的数组: ["CBL202659/A:1","OUTER9:1","PALLET CARDS:1"] 如果我添加另一个托盘卡产品,它将创建一个新条目,而不是将现有项目的数量更新为2 新阵
数组
,这些产品存储为字符串
,格式为productname:quantity
。我遇到的问题是,如果用户添加了一个数量为x的产品,它会按其应该的方式插入到数组中。但是,如果他们随后决定添加更多特定产品,则会在数组中创建一个新条目,而不是检查该产品是否已存在并将数量调整为新值<代码>旧数量+新数量
例如,这是我的数组:
["CBL202659/A:1","OUTER9:1","PALLET CARDS:1"]
如果我添加另一个托盘卡产品,它将创建一个新条目,而不是将现有项目的数量更新为2
新阵列
["CBL202659/A:1","OUTER9:1","PALLET CARDS:1","PALLET CARDS:1"]
我希望数组以如下方式结束:-更新数量
["CBL202659/A:1","OUTER9:1","PALLET CARDS:2"]
目前这是我的代码:
我使用split()
$(".orderBtn").click(function(event){
//Show the order Box
$(".order-alert").show();
event.preventDefault();
//Create the Array
var productArray = [];
//Get reference to the product clicked
var stockCode = $(this).closest('li').find('.stock_code').html();
//Get reference to the quantity selected
var quantity = $(this).closest('li').find('.order_amount').val();
var item = stockCode + ":" + quantity;
var itemCheck = stockCode + ":";
if(quantity == 0){
console.log("Quantity must be greater than 0")
}else{
//If no Cookie exists, create one and add the Array
if ($.cookie('order_cookie') === undefined) {
console.log("CREATE NEW COOKIE");
//Add items to Array
productArray.push(item);
//Add Array to Cookie
$.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
//If the Cookie already exists do this
} else {
productArray = JSON.parse($.cookie('order_cookie'));//get ref to array
if(productArray.indexOf(itemCheck)!= -1){//It exists so update qty
console.log("EXISTS... updating item: " + itemCheck);
//var index = productArray.indexOf(item);
//var update = productArray[index].split(":");
//var name = update[0];
//var oldQty = update[1];
//console.log(name + ":" + oldQty);
//productArray[index] = item;
}else{//It does not exist, so add to array
console.log("Does not exist... adding new item: " + item);
//Append items onto the Array
productArray.push(item);
}
//Update the Cookie
$.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
console.log($.cookie('order_cookie'));
}
//Display the number of items in the Array in the Order Box
$('#order_counter').html(productArray.length);
}
});
我想我在这里要问的真正问题是,是否可以在数组中搜索包含productname:
的子字符串
在接受了一些答案和建议后,我稍微修改了构建数组的方式
但是,我遇到了有关名称-值对的问题
步骤1:获取对库存代码和数量的引用
//Create the Array
var productArray = [];
//Get reference to the product clicked
var stockCode = $(this).closest('li').find('.stock_code').html();
//Get reference to the quantity selected
var quantity = $(this).closest('li').find('.order_amount').val();
在控制台中打印它们以确保它们是正确的
PALLET CARDS
2
步骤2:将它们插入阵列中
productArray.push({stockCode:quantity});
打印它们以确保它们是正确的-这里没有问题
[Object]
0: Object
stockCode: "2" <---------------------- Should be PALLET CARDS: "2"
__proto__: Object
length: 1
__proto__: Array[0]
[对象]
0:对象
股票代码:“2”试试:
var input = ["CBL202659/A:1","OUTER9:1","PALLET CARDS:1","PALLET CARDS:1"],
dict = {},
output = [];
for (var i = 0; i < input.length; i++) {
var parts = input[i].split(':');
if (dict[parts[0]] == undefined) {
dict[parts[0]] = 0;
}
dict[parts[0]] += +parts[1];
}
for (var key in dict) {
output.push([key, dict[key]].join(':'));
}
然而,正如《黑暗的绝对》中提到的那样,您应该最终得到一个类似于以下内容的dict
对象:
Object {CBL202659/A: 1, OUTER9: 1, PALLET CARDS: 2}
并为您提供更多的工作动力。而不是:
var item = stockCode + ":" + quantity;
var itemCheck = stockCode + ":";
...
只要这样做:
编辑:还要检查库存是否已经存在,我认为这会起作用
function checkCode() {
for (var i=0; i<productArray.length;i++) {
if (p[i].stockcode==stockCode) {
p[i].amount+= parseInt(quantity)
}
}
}
if (!checkCode()) productArray.push({ stockcode: stockCode, amount:parseInt(quantity)});
函数检查码(){
对于(var i=0;i考虑重新排列您的结构。像{“CBL202659/A”:1,“OUTER9”:1,“托盘卡”:1}
这样的对象将更易于使用。var item=stockCode+”:“+数量;
是我构建字符串
以进入数组
的代码。我如何修改此代码以匹配您建议的结构?找出问题:“我有一个以字符串形式存储的产品数组。”;-)@Javacadabra我已经更新了我的答案,选择使用原始字符串数组。谢谢你的回答,这很有意义,我可以看到使用字典
对象优于标准数组
。将我当前的数组
转换为这种类型的对象需要大量的工作吗我有3个脚本
使用这个数组
@Javacadabra我不知道需要做多少工作,但是我认为这是值得的。@Javacadabra你自己从HTML创建数组,所以你不需要从数组创建字典,只要从一开始就把它作为一个键/对对象。。是的,我正在工作在@webkit上,我遇到了一个问题。我已经在OP中更新了我的代码,如果你愿意看一下的话,我现在会尝试实现它,非常感谢@webkit
function checkCode() {
for (var i=0; i<productArray.length;i++) {
if (p[i].stockcode==stockCode) {
p[i].amount+= parseInt(quantity)
}
}
}
if (!checkCode()) productArray.push({ stockcode: stockCode, amount:parseInt(quantity)});
var pArray = ["CBL202659/A:1","OUTER9:1","PALLET CARDS:1"];
for (var i =0; i<pArray.length;i++) {
var code = pArray[i].split(":")[0];
var amount = parseInt(pArray[i].split(":")[1]);
if (code==stockCode) {
// code already exists
amount += parseInt(quantity);
pArray[i] = code+":"+amount;
}
}