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
}
我不确定为什么您需要将 subscriptionId 指定为“Id(Type)”,因为它已经在“selectedProducts”类别中。如果纯粹是为了拆分,那么您可以将其排除在外,然后拆分为“,”
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
}