E.g。葡萄应该输出gae。 如果代码的开头看起来像这样,
var words = [ "banana", "apple", "pineapple", "orange", "pear", "grape",
"watermelon", "paragraph", "Avocado", "cherry", "blackberry", "coconut",
"lime", "lemon", "olive", "plum", "Nectarine", "mango", "apricot"];
for (var i = 0; i < 5; i++){
var n1 = Math.floor(rc4Rand.getRandomNumber() * words.length);
var word = words[n1];
document.writeln("The word is: " + word);
document.writeln("1st, middle and last letters are:");
output(word);
}
我应该写像数组n1[0]
,数组[n1.length-1]
,array[length/2]
或者得到什么结果?请提出您的所有意见和建议!
答案 0 :(得分:4)
像这样的东西
var shortened = word.charAt(0) + // first
word.charAt(Math.floor(word.length / 2)) + // middle
word.charAt(word.length-1); // last
答案 1 :(得分:0)
var string = "random string";
var fml; // first middle last
fml = string[0] + string[Math.floor(string.length / 2)] + string[string.length - 1];
// gives "r g"
您可能希望在string
上添加一些检查。如果它是一个空字符串,这将失败。它会短于2个字符,你会得到重复。如果你想绕过另一条路(对于长度均匀的字符串),你也可以用Math.floor
替换Math.ceil
。