我有一个带有一些值的对象。我想在将剩余值添加到新变量时删除部分值。这就是我到目前为止所做的:
var data = {
"selectedProducts": {
"selectedSubscriptionIds": "320151(Products),320145(Products)"
}
};
var SelectedSubscriptionIds = data.selectedProducts.selectedSubscriptionIds;
var StrippedSubscriptionIds = SelectedSubscriptionIds.split("(Products)")[0];
console.log(SelectedSubscriptionIds); //320151(Products),320145(Products)
console.log(StrippedSubscriptionIds); //Returns "320151" only
变量StrippedSubscriptionIds
仅返回第一个剥离值。如何让它循环遍历剥离它们的所有项目,以便只留下数字 - 如320151,320145
...
答案 0 :(得分:2)
SelectedSubscriptionIds.replace(/\(Products\)/g, "").split(",")
答案 1 :(得分:1)
split()函数输出一个项目数组。不是通过“[0]”选择第一个项目,而是将整个数组分配给变量并循环遍历,格式为:
for (var count = 0; count < maxCount; count++) {
// Action to be repeated here
}
您遇到的问题是您的源字符串格式为“Id(Type),Id(Type)”。只拆分“(类型)”会在项目中留下逗号,因此您的剥离项目看起来像“320151”和“,320145”。确保包含逗号(并确保源字符串在末尾也有逗号,或者您的最后一项与分割条件不匹配,并仍然会说“Id(Type)”。
所以你的代码看起来像是:
var data = {
"selectedProducts": {
"selectedSubscriptionIds": "320151(Products),320145(Products),"
}
};
var SelectedSubscriptionIds = data.selectedProducts.selectedSubscriptionIds;
console.log(SelectedSubscriptionIds); //320151(Products),320145(Products),
var subscriptionIdArray = SelectedSubscriptionIds.split("(Products),");
for (var i = 0, i < subscriptionIdArray.length; i++) {
var subscriptionId = subscriptionIdArray[i];
console.log(subscriptionId); // 320151, then 320145 etc
}
我不确定为什么当它已经在“selectedProducts”类别中时需要将subscriptionId指定为“Id(Type)”。如果它纯粹是为了分裂那么你可以把它留下来,然后分开“,”
var data = {
"selectedProducts": {
"selectedSubscriptionIds": "320151,320145"
}
};
var SelectedSubscriptionIds = data.selectedProducts.selectedSubscriptionIds;
console.log(SelectedSubscriptionIds); //320151,320145
var subscriptionIdArray = SelectedSubscriptionIds.split(",");
for (var i = 0, i < subscriptionIdArray.length; i++) {
var subscriptionId = subscriptionIdArray[i];
console.log(subscriptionId); // 320151, then 320145 etc
}
答案 2 :(得分:0)
foreach id in StrippedSubscriptionIds
Console.log(id);
Next
答案 3 :(得分:0)
试
var StrippedSubscriptionIds = SelectedSubscriptionIds.split("(Products),");
StrippedSubscriptionIds[-1] = StrippedSubscriptionIds[-1].substr(0, StrippedSubscriptionIds[-1].length - 10);
你有一个数组。
最后一个代码行删除了尾随的(Product)
字符串。
或者,使用:
var temp = SelectedSubscriptionIds.replace(/\(Products\)/g, "");
var StrippedSubscriptionIds = temp.split(",");