集合与地图类型
·
Yin灏
集合类型
集合(set)内含均不重复的的元素
// 集合类型
let actions = new Set();
actions.add('read')
actions.add('write').add('update')
actions.add('delete')
console.log(actions); // Set(4) { "read", "write", "update", "delete" }
actions.add('read').add('read').add('delete').add('write').add('update')
console.log(actions) // { "read", "write", "update", "delete" }
console.log(actions.entries()); // SetIterator {"read" => "read", "update" => "update", "delete" => "delete"}
console.log(actions.keys()); // Set Iterator { }
console.log(actions.values()); // Set Iterator { }
for(let element of actions) {
console.log(element); // "read", "write", "update", "delete"
}
console.log(actions.size); // 4
console.log(actions.has('hide')); // false
console.log(actions.has('write')); // true
地图类型
地图(map)内含键值对类型,键可以是任意类型。
let items = new Map();
items.set('slipper', 50);
items.set('shoes', 200);
items.set('pants', 100).set('shift', 150);
console.log(items); // { slipper → 50, shoes → 200, pants → 100, shift → 150 }
console.log(items.size); // 4
console.log(items.entries()); // Map Iterator { }
console.log(items.keys()); // Map Iterator { }
console.log(items.values()); // Map Iterator { }
for(let [ product, price ] of items) {
console.log(`One ${product} costs ${price}.`)
}
/*
One slipper costs 50.
One shoes costs 200.
One pants costs 100.
One shift costs 150.
*/