Performance. Although the JavaScript language itself (in a narrow sense, does not contain extensions such as DOM) in most cases will not cause performance problems, it is unfortunately a question, so the interviewer will still take performance as a test site.
Before proceeding, we recommend that you implement a version that you think is the best.
Intuitive solutionFor array deduplication, as long as the program is written, the first solution can be obtained immediately:
function unique(arr) { var ret = [] for (var i = 0; i < arr.length; i++) { var item = arr[i] if (ret.indexOf(item) === -1) { ret.push(item) } } return ret}
Code laycode-v1.1Intuition is often very reliable. In modern browsers, the above function is very correct and the performance is good. However, the biggest sorrow of the front-end is the challenge of supporting various runtime environments. The indexOf method of the array does not exist in the IE6-8. The intuitive solution should be slightly transformed:
var indexOf = [].indexOf ? function(arr, item) { return arr.indexOf(item) } : function indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) { return i } } return -1 }function unique(arr) { var ret = [] for (var i = 0; i < arr.length; i++) { var item = arr[i] if (indexOf(ret, item) === -1) { ret.push(item) } } return ret}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
Code laycode-v1.1This step is correct, but in terms of performance, the Dual Loop will make the interviewer uncomfortable.
Optimization SchemeWhen it comes to optimization, there are always a lot of flowers and flowers. But the Eight Immortals are often not grounded, and Baihua is easy to attract bugs. The optimization schemes for Array deduplication are not discussed here. The following describes only one of the most commonly used methods with good results.
function unique(arr) { var ret = [] var hash = {} for (var i = 0; i < arr.length; i++) { var item = arr[i] var key = typeof(item) + item if (hash[key] !== 1) { ret.push(item) hash[key] = 1 } } return ret}
Code laycode-v1.1The core is to build a hash object to replace indexOf. note that in JavaScript, the key value of an object can only be a string. Therefore, var key = typeof (item) + item must be used to distinguish between value 1 and string '1.