实现说明
主线是函数 describeSelection的调用过程。
守卫条件成立时抛出 Error,而不是返回一个假值。
使用要点
- 这是浏览器侧代码——
document在 Node 里解析不到。 - 守卫
!select满足时靠提前的throw短路流程。 - 直接运行文件,输出会带上标签,比如
selected: $——输出的每一行都能指回产生它的那次调用。
常见问题
坏输入有失败路径吗?
代码会抛出 Error——守卫条件 !select 会在主逻辑之前拦下坏状态。请在调用点处理,或有意让它向上传播。
「select 元素的选项读取」能在裸 Node.js 里跑吗?
不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。
入口签名:function describeSelection()
核心语句
return `${select.value} @ index ${select.selectedIndex} (${option?.text ?? "none"})`;
select.addEventListener("change", () => {
console.log(describeSelection());
// selectedOptions 处理 multiple 场景:单选时长度恒为 1
const chosen = [...select.selectedOptions].map((option) => option.value);
console.log(`selected: ${chosen.join(",")}`);
});
if (!select) throw new Error("select markup missing");
代码示例
const select = document.querySelector<HTMLSelectElement>("#env");
if (!select) throw new Error("select markup missing");
function describeSelection(): string {
// value 总是字符串;selectedIndex 指向 options 里的位置
const option = select.options[select.selectedIndex];
return `${select.value} @ index ${select.selectedIndex} (${option?.text ?? "none"})`;
}
console.log(describeSelection());
select.addEventListener("change", () => {
console.log(describeSelection());
// selectedOptions 处理 multiple 场景:单选时长度恒为 1
const chosen = [...select.selectedOptions].map((option) => option.value);
console.log(`selected: ${chosen.join(",")}`);
});
// 程序化切换与手动选择走同一条 change 路径
select.value = "staging";
select.dispatchEvent(new Event("change"));