javascript 提供了两种强大的数据结构来存储集合:set 和 array。虽然两者都可以存储多个值,但它们独特的特性使它们更适合不同的场景。让我们探讨一下您何时以及为何会选择其中之一。
set 最显着的特点是它自动处理重复项。
// arrays allow duplicates const arr = [1, 2, 2, 3, 3, 4]; console.log(arr); // [1, 2, 2, 3, 3, 4] // sets automatically remove duplicates const set = new set([1, 2, 2, 3, 3, 4]); console.log([...set]); // [1, 2, 3, 4] // removing duplicates from an array using set const uniquearray = [...new set(arr)]; console.log(uniquearray); // [1, 2, 3, 4]
set 提供更快的查找时间来检查元素是否存在。
const largearray = array.from({ length: 1000000 }, (_, i) => i);
const largeset = new set(largearray);
// array lookup
console.time('array includes');
console.log(largearray.includes(999999));
console.timeend('array includes');
// set lookup
console.time('set has');
console.log(largeset.has(999999));
console.timeend('set has');
// set is significantly faster because it uses hash table internally
数组提供了更多内置的数据操作方法,而集合则专注于唯一性管理。
// array methods const arr = [1, 2, 3, 4, 5]; arr.push(6); // add to end arr.pop(); // remove from end arr.unshift(0); // add to beginning arr.shift(); // remove from beginning arr.splice(2, 1, 'new'); // replace elements arr.slice(1, 3); // extract portion arr.map(x => x * 2); // transform elements arr.filter(x => x > 2); // filter elements arr.reduce((a, b) => a + b); // reduce to single value // set methods const set = new set([1, 2, 3, 4, 5]); set.add(6); // add value set.delete(6); // remove value set.has(5); // check existence set.clear(); // remove all values
数组维护插入顺序并提供基于索引的访问,而集合仅维护插入顺序。
// array index access const arr = ['a', 'b', 'c']; console.log(arr[0]); // 'a' console.log(arr[1]); // 'b' arr[1] = 'x'; // direct modification // set has no index access const set = new set(['a', 'b', 'c']); console.log([...set][0]); // need to convert to array first // no direct index modification possible
集合通常比数组使用更多的内存,但提供更快的查找速度。
// memory comparison (rough example)
const numbers = array.from({ length: 1000 }, (_, i) => i);
// array memory
const arr = [...numbers];
console.log(process.memoryusage().heapused);
// set memory
const set = new set(numbers);
console.log(process.memoryusage().heapused);
// set typically uses more memory due to hash table structure
// 1. when order and index access matters const playlist = ['song1.mp3', 'song2.mp3', 'song3.mp3']; const currenttrack = playlist[currentindex]; // 2. when you need array methods const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(x => x * 2); const sum = numbers.reduce((a, b) => a + b, 0); // 3. when duplicates are acceptable or desired const votes = ['yes', 'no', 'yes', 'yes', 'no']; const yesvotes = votes.filter(vote => vote === 'yes').length;
// 1. when tracking unique values
const uniquevisitors = new set();
function logvisitor(userid) {
uniquevisitors.add(userid);
console.log(`total unique visitors: ${uniquevisitors.size}`);
}
// 2. for quick lookup operations
const allowedusers = new set(['user1', 'user2', 'user3']);
function checkaccess(userid) {
return allowedusers.has(userid);
}
// 3. for removing duplicates
function getuniquehashtags(posts) {
const uniquetags = new set();
posts.foreach(post => {
post.hashtags.foreach(tag => uniquetags.add(tag));
});
return [...uniquetags];
}
您可以在需要时轻松在集合和数组之间进行转换。
// Array to Set const arr = [1, 2, 2, 3, 3, 4]; const set = new Set(arr); // Set to Array - three methods const back1 = [...set]; const back2 = Array.from(set); const back3 = Array.from(set.values()); // Useful for array deduplication const deduped = [...new Set(arr)];
需要时选择数组:
需要时选择设置:
请记住,您随时可以在需要时在两种类型之间进行转换,因此请选择最适合您当前需求的一种。
以上就是JavaScript 中的集合与数组:何时使用哪个?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号