In the actual project, we often have the following requirements:
Get the value of a key from a map, if you find that the value of the corresponding key is NULL, create a value for the key (typically the initial value), and then save the value back to the map with the following code:
var value = map[key];if(value == null){ value = ""; map[key] = value;}
But I always feel this code is disgusting, why, too verbose, too long. In real-world projects, this is a lot of skill, and if it's everywhere, it's going to crash. The villain must die.
# #赋值操作合并
First of all, value = "" and Map[key] = value These two lines do not need to be written in two lines, are assigned, should be this can be optimized:
var value = map[key];if(value == null){ value = map[key] = "";}
Remove if judgment
If you change the if judgment to a ternary operator, you can reduce the code as follows:
var value = map[key]; value = (value == null) ?( map[key] = "") : value;
If you use | | Symbols that look more convenient:
var value = map[key]; value = value || (map[key] = "");
Of course, these two lines of code can eventually be combined into the following code:
var value = map[key] || (map[key] = "");
At this point, the final 5 lines of code are simplified into one line of code.
# #另外一个答案
Take this question to the company's small partner, here is another answer:
var value = map[key] = map[key] || ""
# #总结
This question is not difficult, ask the small partner, some people can also give the correct answer. But usually no one to take the initiative to think.
Welcome attention to the public number:
Simplifying a section of JavaScript code