简体   繁体   English

For-Of 循环“Set 不是函数”

[英]For-Of Loop "Set is not a function"

I have this code here:我在这里有这个代码:

function Duplicate(array1, array2){
    var wordSet = new Set();
    var result = [];

    console.log(wordSet)
    for(let letter of array1){
       if(!wordSet(array1[letter])){
           wordSet.add(array1[letter])
       }
    }

    for(let word of wordSet){
        result.push(word)
    }

    return result;
}

console.log(Duplicate(['a','b','c'],['a','k','d','m','k']))

However, when I tried to run it, it says "wordSet is not a function".但是,当我尝试运行它时,它说“wordSet 不是函数”。 If I use the regular "for..." loop it would work fine.如果我使用常规的“for...”循环,它会正常工作。 Does anyone know what the problem here is?有谁知道这里的问题是什么?

As mentioned in the comment, wordSet is not a function so you can not call it.正如评论中提到的, wordSet 不是一个函数,所以你不能调用它。 I think the commenter is right that you are after using has with your set.我认为评论者是对的,你在使用 has 和你的套装后是正确的。 Sets are unique (you probably already knew that).集合是独一无二的(你可能已经知道了)。 Sets can be used with for...of loops and de-structured.集合可以用于 for...of 循环和解构。

for(let word of wordSet) // this is allowable

I am not sure what you are after in this area of the code as you can simply just add each letter of the array to the Set and it will only keep the unique ones with no duplicates.我不确定你在代码的这个区域想要什么,因为你可以简单地将数组的每个字母添加到 Set 中,它只会保留唯一的没有重复的字母。 You never use array2 in the function.您永远不会在函数中使用 array2。 Are you trying to find the duplicate letters in array1 and array2?您是否试图在 array1 和 array2 中找到重复的字母?

If so you could do the following:如果是这样,您可以执行以下操作:

1) load one Set with the each array item by using add (add each letter, the set will only keep the unique ones) 1) 使用 add 为每个数组项加载一个 Set(添加每个字母,该集合将只保留唯一的)

2) using the second array you can search the against the set, something like: 2) 使用第二个数组,您可以针对集合进行搜索,例如:

for (let val of array2){ // look at each letter in the array
   if (wordSet.has(val)){ // if that letter is in your unique set from array 1
      result.push(val);  // push it onto your duplicate only array
   } // end if
} // end for

return result; // return the duplicate array to the caller

This whole thing might be more efficient using 2 sets (a set of unique letters for each array).使用 2 个集合(每个数组的一组唯一字母)可能会更有效。 Depends what you are after really.取决于你真正追求的是什么。

Hope this helps you along the way.希望这对您有所帮助。 -WWC -WWC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM