我有一个字符串,我想要的重复字母,字母重复更多,然后一次只显示一次。例如我有一个字符串aaabbbccc我想要的结果是abc。到目前为止我的函数工作原理如下:如果信件不重复它没有显示如果它重复一次只显示一次(如果aa显示a)如果重复两次显示所有(如果aaa显示aaa)如果它的重复3次它显示6(如果aaaa显示aaaaaa)
I have a string with repeated letters i want, letter that are repeated more then once to show only once. for instance I have a string aaabbbccc i want the result to be abc. so far my function works like this: if the letter doesn't repeat its not shown if its repeated once its show only once (if aa shows a) if its repeated twice shows all(if aaa shows aaa) if its repeated 3 times it shows 6( if aaaa shows aaaaaa)
function unique_char(string){ var str_length=string.length; var unique=''; var count=0; for(var i=0; i<str_length; i++){ for(var j=i+1; j<str_length; j++){ if(string[i]==string[j]){ count++ unique+=string[i]; } } } return unique; } document.write( unique_char('aaabbbccc'))函数必须在循环内,这是为什么第二个在第一个
function must be with loop inside a loop that's why the second for is inside the first
推荐答案请先将其存储到数组,然后使用回答此处,然后重新加入,如下所示:
Convert it to an array first, then use the answer here, and rejoin, like so:
var nonUnique = "ababdefegg"; var unique = nonUnique.split('').filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');全部在一行中: - )
All in one line :-)
更多推荐
只显示字符串中的唯一字符一次
发布评论