连接时如何删除数组中的最后一个白色space?
How to delete last white space in the array when concatenating?
我需要一个 JavaScript 提醒,最后一个词和感叹号之间没有 space。
最终警报应如下所示:
I like my own garden verymuchmuch verymuchmuch!
这是我之前 space 使用的代码。
var inittext, closetext, msg = "";
var i, j, k;
var myarray = new Array(3);
myarray[0] = "my";
myarray[1] = "own";
myarray[2] = "garden";
inittext = "I like ";
closetext = "!";
for (k=0; k < 3; k++) {
inittext = inittext + myarray[k] + " ";
}
for (j=0; j < 2; j++){
inittext = inittext + "very";
for (i=0; i < 2; i++){
inittext = inittext + "much";
}
inittext = inittext +" ";
}
msg = inittext + closetext;
alert(msg);
看起来 closetext 变量包含 !并且 inittext 是添加额外 space 的地方,因为 inittext + " " 即使在最后一次调用之后什么也没有,所以 try
msg = inittext.trim() + closetext;
你可以这样检查不添加白色space:
var inittext, closetext, msg = "";
var i, j, k;
var myarray = new Array(3);
myarray[0] = "my";
myarray[1] = "own";
myarray[2] = "garden";
inittext = "I like ";
closetext = "!";
for (k=0; k < 3; k++) {
inittext = inittext + myarray[k] + " ";
}
for (j=0; j < 2; j++){
inittext = inittext + "very";
for (i=0; i < 2; i++){
inittext = inittext + "much";
}
inittext = inittext + (j<1 ? " " : "");
}
msg = inittext + closetext;
alert(msg);
或者你可以 trim inittex 变量 msg = inittext.trim() + closetext;
我需要一个 JavaScript 提醒,最后一个词和感叹号之间没有 space。
最终警报应如下所示:
I like my own garden verymuchmuch verymuchmuch!
这是我之前 space 使用的代码。
var inittext, closetext, msg = "";
var i, j, k;
var myarray = new Array(3);
myarray[0] = "my";
myarray[1] = "own";
myarray[2] = "garden";
inittext = "I like ";
closetext = "!";
for (k=0; k < 3; k++) {
inittext = inittext + myarray[k] + " ";
}
for (j=0; j < 2; j++){
inittext = inittext + "very";
for (i=0; i < 2; i++){
inittext = inittext + "much";
}
inittext = inittext +" ";
}
msg = inittext + closetext;
alert(msg);
看起来 closetext 变量包含 !并且 inittext 是添加额外 space 的地方,因为 inittext + " " 即使在最后一次调用之后什么也没有,所以 try
msg = inittext.trim() + closetext;
你可以这样检查不添加白色space:
var inittext, closetext, msg = "";
var i, j, k;
var myarray = new Array(3);
myarray[0] = "my";
myarray[1] = "own";
myarray[2] = "garden";
inittext = "I like ";
closetext = "!";
for (k=0; k < 3; k++) {
inittext = inittext + myarray[k] + " ";
}
for (j=0; j < 2; j++){
inittext = inittext + "very";
for (i=0; i < 2; i++){
inittext = inittext + "much";
}
inittext = inittext + (j<1 ? " " : "");
}
msg = inittext + closetext;
alert(msg);
或者你可以 trim inittex 变量 msg = inittext.trim() + closetext;