题目
Write a function that returns a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than two characters or longer than 100 characters, the function should return “invalid string”.
编写一个函数,返回字符串中所有偶数位置的字符(索引以1开头)。如果字符串小于两个字符或长于100个字符,则函数应返回“invalid string”。
例子
"abcdefghijklm" --> ["b", "d", "f", "h", "j", "l"]
"a" --> "invalid string"
题解一
// 题解一:
function evenChars(string) {
if(string.length < 2 || string.length > 100) return 'invalid string';
var arr = [];
for(let i=0;i<[...string].length;i++){ // [...string] 将字符串转成数组
if(i%2 == 1) arr.push([...string][i]);
}
return arr;
}
题解二
// 题解二:
// JavaScript Array filter() 方法
// filter() 方法返回数组,包含了符合条件的所有元素。
function evenChars(string) {
return (string.length < 2 || string.length > 100) ? 'invalid string' : [...string].filter((value,index) => index%2)
}