![](/img/trans.png)
[英]How to change all the elements but the first one in the array to only present the difference
[英]Javascript How to identify if all elements of one array are present in another
我需要创建一个函数来检查两个字符串数组的第二个字符串中的所有字母是否都存在于第一个字符串中。 我编写的函数似乎可以用在我尝试过的大多数示例中,但是[hello],“ hey”]返回true,尽管您好,而我也不知道为什么。
这是我的代码:
function mutation(arr) {
arr[0] =arr[0].toUpperCase().split("");
arr[1] =arr[1].toUpperCase().split("");
for(i=0;i<arr[1].length;i++){
if(arr[0].indexOf(arr[1][i])>=0){
return true;
} else {return false;}}}
mutation(["hello", "Hey"]);
即使一个字符匹配,您也将返回true,请尝试以下代码,它检查所有字符是否存在
function mutation(arr) {
arr[0] = arr[0].toUpperCase().split("");
arr[1] = arr[1].toUpperCase().split("");
var count = 0;
for (i = 0; i < arr[1].length; i++) {
if (arr[0].indexOf(arr[1][i]) >= 0) {
count++;
}
}
return count === arr[1].length
}
mutation(["hello", "Hey"]);
这是一种更有效的解决方案,仅适用于小写字母。
(function(){ function charCode(str, i){ return str.charCodeAt(i) - 97; } function isMutation(a,b){ const aArr = new Uint8Array(26); const bArr = new Uint8Array(26); let i=0; let index = 0; while(i<a.length){ ++aArr[charCode(a, i)]; ++i; } i = 0; while(i<b.length){ ++bArr[charCode(b, i)]; ++i; } i = 0; while(i < 26){ if(!(aArr[i]===0 && bArr[i]===0 || aArr[i]>0 && bArr[i]>0)){ return false } ++i; } return true; } console.assert(isMutation('hello', 'oleh') === true); console.assert(isMutation('hello', 'hey') === false); })();
您还可以比较两个数组中uniq字符的总和,但是在这种情况下,您只需将每个字母相加一次。
我建议使用georg用户在“ 从JavaScript数组中删除重复项”中建议的代码解决方案之一。
例如,下面的函数可用于对每个数组(arr[0] and arr[1])
进行排序并删除重复项。
在上面的链接中感谢georg用户。
function uniq(a) {
return a.sort().filter(function(item, pos, ary) {
return !pos || item != ary[pos - 1];
})
}
对重复项进行排序/删除后,可以测试一下两个返回的字符串是否相等。
你好=> EHLO,嘿=> EHY
H!===
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.