你的問題使得它看起來像你想的一件事,但是你的示例代碼看起來像你想要別的東西。第一個功能是你的問題使得它聽起來像你想要的,第二個是你的示例代碼似乎表明了什麼。
功能1:
function capLength(str1, str2, name1, name2, name3) {
// Join the strings and get the resulting length.
// (This is the same as str1 + str2... just marginally faster.)
var totalLength = [str1, str2, name1, name2, name3].join("").length;
var excessLength = totalLength - 100;
if (excessLength <= 0) {
return; // If the string isn't too long, no changes are needed.
}
// Available length for the variable strings (combined) will be
// 100 - combined length of the constant strings.
// To get the length of each one, we divide by two.
var str1Length = (100 - name1.length - name2.length - name3.length)/2;
var str2Length = (100 - name1.length - name2.length - name3.length)/2;
// It's possible that one string will be under the limit and one will be over.
// Move the available length from one to the other
while (str1Length > str1.length) {
str1Length--;
str2Length++;
}
while (str2Length > str2.length) {
str2Length--;
str1Length++;
}
str1 = str1.substring(0, str1Length - 3) + "...";
str2 = str2.substring(0, str2Length - 3) + "...";
return [str1, str2, name1, name2, name3];
}
功能2:
function capLength(str1, str2, name1, name2, name3) {
// Join the strings and get the resulting length.
// (This is the same as str1 + str2... just marginally faster.)
var totalLength = [str1, str2, name1, name2, name3].join("").length;
var excessLength = totalLength - 100;
if (excessLength <= 0) {
return; // If the string isn't too long, no changes are needed.
}
// Available length for the variable strings (combined) will be
// 100 - combined length of the constant strings.
// To get the length of each one, we divide by two.
var str1Length = (100 - name1.length - name2.length - name3.length)/2;
var str2Length = (100 - name1.length - name2.length - name3.length)/2;
// It's possible that one string will be under the limit and one will be over.
// Move the available length from one to the other
while (str1Length > str1.length) {
str1Length--;
str2Length++;
}
while (str2Length > str2.length) {
str2Length--;
str1Length++;
}
var str1Mid = str1.length/2;
var str2Mid = str2.length/2;
if (str1.length != str1Length) {
str1 = (str1.substring(0, str1.length/2) + "...").substring(0, str1Length);
}
if (str2.length != str2Length) {
str1 = (str2.substring(0, str2.length/2) + "...").substring(0, str2Length);
}
return [str1, str2, name1, name2, name3];
}
你嘗試過這麼遠嗎?你有一些代碼可以共享(即使它目前不工作)? –