Zla*_*niq 6 javascript string character unique
我有一个重复字母的字符串.我希望不止一次重复的字母只显示一次.例如,我有一个字符串aaabbbccc我希望结果是abc.到目前为止我的功能是这样的:
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
Run Code Online (Sandbox Code Playgroud)
该函数必须在循环内循环; 这就是为什么第二个for在第一个内部.
小智 20
首先将它转换为数组,然后在这里使用答案,并重新加入,如下所示:
var nonUnique = "ababdefegg";
var unique = nonUnique.split('').filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
Run Code Online (Sandbox Code Playgroud)
全部在一行:-)
le_*_*e_m 16
填充Set字符并连接其唯一条目:
function makeUnique(str) {
return String.prototype.concat(...new Set(str))
}
console.log(makeUnique('abc')); // "abc"
console.log(makeUnique('abcabc')); // "abc"Run Code Online (Sandbox Code Playgroud)
根据实际问题:“如果字母不重复,则不会显示”
function unique_char(str)
{
var obj = new Object();
for (var i = 0; i < str.length; i++)
{
var chr = str[i];
if (chr in obj)
{
obj[chr] += 1;
}
else
{
obj[chr] = 1;
}
}
var multiples = [];
for (key in obj)
{
// Remove this test if you just want unique chars
// But still keep the multiples.push(key)
if (obj[key] > 1)
{
multiples.push(key);
}
}
return multiples.join("");
}
var str = "aaabbbccc";
document.write(unique_char(str));
Run Code Online (Sandbox Code Playgroud)