我正在尝试在 xpages 应用程序中申请循环。
在计算字段中,我放入了以下代码,它显示了预期的结果。
var msg = "";
for(var j = 1; j <5;j++)
{
msg += "* This message is from " +j +" " ;
}
return msg;
//Result will show something like this
//"* This message is from 1 * This message is from 2 * This message is from 3 * This message is from 4 * This message is from 5 "
假设在页面A中有一个多行编辑框,它使用sessionScope变量(ssvTopic)。在页面 B 中有一个计算字段,我可以使用此代码显示多行编辑框中的值
sessionScope.ssvTopic
这很好用。现在我尝试在 for 循环中应用 sessionScope 变量。
var msg ="";
var value = sessionScope.ssvTopic
for(var i =0; i< value.length; i++)
{
msg += "* This message is from " + value+" " ;
}
return msg;
当我运行应用程序时,我注意到 value.length 表示值中的字符数。我的意思是如果 sessionScope.ssvTopic 值是生活方式,新闻,体育,字符是 24,那么在 for 循环中,消息将显示 24 次。
所以我将代码 value.length 更改为 @Count(value)。当我运行应用程序时,消息只显示一次。
var msg ="";
var value = sessionScope.ssvTopic
for(var i =0; i< @Count(value); i++)
{
msg += "* This message is from " + value+" " ;
}
return msg;
//The result display like this, it only display one time
//* This message is from life style, news, sports
我认为@Count(value) 接近结果(与value.length 比较),但我不明白为什么它只显示一次消息。
我也尝试将 sessionScope 值放在一个数组中,但结果是一样的,它只显示一条消息。
var msg ="";
var value = sessionScope.ssvTopic
var valueArray = new Array();
viewScope.put("valueArray", @Implode(valueArray, ",")) ;
valueArray.push(value);
//no matter if I use @Count(valueArray) or valueArray.length, the result does not have difference
for(var i =0; i< @Count(valueArray); i++)
{
msg += "* This message is from " + valueArray+" " ; //no matter if I use valueArray or valueArray[i], the result does not have difference too
}
return msg;
我不确定我错了哪一部分。我打算做的是显示消息的数量取决于 sessionScope 变量值的数量。在我的例子中,如果 sessionScope 变量包含生活方式、新闻、体育,结果将是这样的
* This message is from life style * This message is from news * This messages is from sports
如果我再次运行这段代码,它会正常工作。
var msg = "";
for(var j = 1; j <5;j++)
{
msg += "* This message is from " +j +" " ;
}
return msg;
所以我只是将“5”更改为sessionScope变量,它不会显示消息的数量取决于sessionScope变量值的数量。
谁能告诉我如何解决这个问题。非常感谢。
(快速更新)
我尝试了以下代码,但它没有返回任何内容。
for(var i =0; i< sessionScope.ssvTopic; i++)
{
msg += "* This message is from " + ssvTopic[i]+" " ; // with [i] or without [i], the result is the same, it does not return anything
}
return msg;
我没有返回消息,而是尝试返回其他东西,例如@Count(value)、@Count(valuArray)、valueArray.length。
@Count(value) //this returns 1.0
@Count(valueArray) //this returns 1.0
valueArray.length //this returns 1.0
value.length //this return 24.0 as mentioned above, this returns the number of characters of the value
因此我注意到这是代码中的一个错误,但我不明白该错误只为结果返回 1.0。
最佳答案
你只错过了一点让它工作的东西:
var msg = "";
var value = sessionScope.ssvTopic.split('\n');
for(var i = 0; i < value.length; i++) {
msg += "* This message is from " + value[i] + " " ;
}
return msg;
多行编辑框返回多行字符串,而不是字符串数组。所以,你需要 split字符串首先换行。然后您可以使用生成的数组。
(@Count 总是返回 1,因为多行编辑框的值只有 一个 字符串)
关于xpages - for 循环中的 SessionScope 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42638526/