例: 'ascxda'和'asaxcd',返回true ; 'qweq'和'qwqp',返回false。
方法一:
function fn(str1,str2){
str1 = str1.split('').sort((a,b)=>a.charCodeAt()-b.charCodeAt()).join('');
str2 = str2.split('').sort((a,b)=>a.charCodeAt()-b.charCodeAt()).join('');
if(str1 === str2){
return true
}
else {
return false
}
}
let fn1 = fn("ascxda", "asaxcd");
console.log(fn1);//true
let fn2 = fn("qweq", "qwqp");
console.log(fn2);//false
方法二:
function fn(str1='',str2=''){
str1 = str1.split('');
str2 = str2.split('');
if(str1.length !== str2.length){
return false;
}
for(let i = 0;i<str1.length;i++){
let cur = str1[i];
let index = str2.indexOf(cur);//返回的是当前项的索引
if (index!==-1){
// 存在当前项,就删除str2中的那一项删除掉
str2.splice(index,1)
}
else {
// 不存在当前项
return false;
}
}
return true;
}
let fn1 = fn("ascxda", "asaxcd");
console.log(fn1);//true
let fn2 = fn("qweq", "qwqp");
console.log(fn2);//false