我有一个数组,需要在循环内按3个值进行分组。
所以首先我需要3个值,然后循环并获取3个下一个值,依此类推。
在下面的代码中,我需要读取前3个数组值并遍历代码,然后获取下3个数组值。
数据如下:title1,text1,image1,title2,text2,image2,title3,text3,image3
。
并且是我服务器的回调。
var myString = data;
var arr = myString.split(',');
var notisTitle = arr[0];
var notisMessage = arr[1];
var notisImage = arr[2];
// I need to loop this - first with the first 3 array values
// and the next time with the next 3 array values etc.
myApp.addNotification({
title: notisTitle,
message: notisMessage,
media: '<img width="44" height="44" style="border-radius:100%;margin-top:-10px;" src="'+notisImage+'">',
closeOnClick: true,
onClose: function (data) {
}
});
“数据”是来自我的服务器(经典的ASP)的回调,它从下面获取“内容”。
datan = Array (notisTitle, notisMessage, notisImage)
for i = 0 to ubound(datan)
content = datan(0) & "," & datan(1) & "," & datan(2) & ","
next
response.write content
最佳答案
这应该满足您的需求:-
var myString = data;
var arr = myString.substring(0, myString.length - 1).split(','); // remove last comma
for (var i = 0, l = arr.length; i < l; i++) {
var notisTitle = arr[i];
var notisMessage = arr[++i];
var notisImage = arr[++i];
//I need to loop this - first with the first 3 array values
//and the next time with the next 3 array values etc...
myApp.addNotification({
title: notisTitle,
message: notisMessage,
media: '<img width="44" height="44" style="border-radius:100%;margin-top:-10px;" src="' + notisImage + '">',
closeOnClick: true,
onClose: function(data) {
}
});
}
更新
如果
data
像这样设置myString
:-var myString = 'App Notis 2,Notis text 2,http://www.manmade.se/appmanager/admin/user_images/skolappen/splash/196x196.png,App Notis 3,Notis text 3,http://www.manmade.se/appmanager/admin/user_images/skolappen/notiser/background_webb.jpg,';
这样,在
,
上拆分时,数组中将有7个项目。因为最后有一个,
给出索引6 ""
。当你说:
感谢BG101,但是它第一次循环了“ myApp.addNotification”
值是否为空?
我认为您的问题是这个,但不是第一次而是最后一次迭代。
从字符串末尾删除
,
并尝试。更新2
最后一个逗号可以这样删除:-
myString.substring(0, myString.length - 1).split(',');
往上看。