Angular 2中Set的浏览器兼容性与遍历问题咨询
Hey there! Let's tackle your two concerns step by step:
First, let's address the browser compatibility worry. While it's true that older browsers like IE11 don't support Set, most modern browsers (Chrome, Firefox, Edge, Safari) have solid support for it now. But if you need to cover legacy environments, here are two reliable alternatives:
Array with Deduplication Checks: Maintain an array to store selected users, and add a check to avoid duplicates:
selectedUsers: User[] = []; // Replace User with your actual user type // When adding a user if (!this.selectedUsers.includes(e)) { this.selectedUsers.push(e); }This approach has universal browser support and is straightforward to implement.
Object as a Map: Use an object where keys are unique identifiers of your users (like
id) and values are the user objects themselves:selectedUsersMap: { [userId: string]: User } = {}; // When adding a user this.selectedUsersMap[e.id] = e;Checking if a user is already selected is as simple as
if (e.id in this.selectedUsersMap), and this method also offers fast lookups and deletions.
The error "The Type Set is not Array" usually stems from TypeScript not recognizing the Set type correctly, or missing proper type definitions. Try these solutions:
Configure TypeScript Correctly: Ensure your
tsconfig.jsonhas the right settings to support ES6+ features:{ "compilerOptions": { "target": "es6", // Or higher like es2017 "lib": ["es2017", "dom"] // Includes type definitions for Set and other ES6+ features } }Explicitly Define the Set's Generic Type: Declare your Set with the specific type of your user objects so TypeScript knows what it's dealing with:
mySet: Set<User> = new Set<User>(); // Replace User with your user typeConvert Set to Array for Iteration: If the above fixes don't work, you can convert the Set to an array and iterate over that instead—TypeScript will have no issue with array iteration:
// Using Array.from() Array.from(this.mySet).forEach(entry => console.log(entry)); // Or using spread operator [...this.mySet].forEach(entry => console.log(entry));
内容的提问来源于stack exchange,提问作者parvaneh

