let in switch cases error

解決在switch cases中let相同變數名稱噴error小技巧

Keyo
Keyo
Sep 9, 2018 · 2 min read

範例

function doSomeThing(arg) {
switch (arg) {
case 1:
let name = 'Keyo';
break;
case 2:
let name = 'yo32310';
break;
default:
break;
}
}
Error--> Duplicate declaration "name"

解決方法就是{包起來就對了}

function doSomeThing(arg) {
switch (arg) {
case 1: {
let name = 'Keyo';
}
break;
case 2: {
let name = 'yo32310';
}
break;
default: {

}
break;
}
}

但如果name 要在switch之後還會需要,那就是往外拉

例如

function doSomeThing(arg) {
let name ;
switch (arg) {
case 1:
name = 'Keyo';
break;
case 2:
name = 'yo32310';
break;
default:
name = 'other';
break;
}
return name
}

mis101247

程式設計/邏輯解題/生活/旅遊/知識

Keyo

Written by

Keyo

任職於AIII.AI擔任FullStack。喜歡學習嘗試新事物,所學不侷限於目前職業所需的知識。讓我們一起成長一起改變世界!!

mis101247

mis101247

程式設計/邏輯解題/生活/旅遊/知識

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade