Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - Is it possible to convert many if/else statements to a dictionary for space efficiency?

In Javascript is it possible to convert many if/else statements to a dictionary for space efficiency?

For example I have the following which is longer in reality

if (namelen < 20) {
form.innerHTML = 'hurray!';
}
else if (namelen > 20 && lastname < 90) {
form.innerHTML = 'too long';
}
else if (namelen > 90 && lastname < 120) {
form.innerHTML = 'go away you cheater';
}
...

Is there a way to make that into a dictionary for space efficiency?

maybe something like

var diction = {namelen < 20: 'hurray', namelen > 20: 'too long', lastname < 90: 'too long', namelen > 90: 'go away you cheater', namelen < 120: 'go away you cheater'}

If not a dictionary, how would I refactor that many if else? bear in mind that I'm new to JS and can have missed some important features, and before you ask I spend most of the day reading programming books and the rest of the day coding.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could try something like this:

var dict = [
    { max: 0 },
    { max: 20,  str: 'hurray!' },
    { max: 90,  str: 'too long' },
    { max: 120, str: 'go away you cheater' }
];
for(var i = 1; i < dict.length; i++){
    if(namelen > dict[i-1].max && lastname < dict[i].max){
        form.innerHTML = dict[i].str;
    }
}

So, if namelen is greater than the "previous max", and lastname is less than max, set the innerHTML.

Notice that I initialized my i as 1, so the for loop will start looking at dict[1]. This way, I can use that first object in to make namelen > dict[i-1] work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...