We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
类型:高频面试题 难度:★★
请编写一个数组去重函数(用 ES5、ES6 各写一个)
function removeRepeat(arr) { // 你的代码 }
参考答案:
// 对象属性法 // 注意:[1, '1'] 形式的数组会产生误差,因为 hash[1] === hash['1'] function removeRepeat(arr) { var result = [], hash = {}; for (var i = 0, elem; i < arr.length; i++) { elem = arr[i]; if (!hash[elem]) { result.push(elem); hash[elem] = true; } } return result; } // 指针查询法 function removeRepeat(arr) { var result = []; arr.map(function(item, idx, array) { if (array.indexOf(item) === idx) { result.push(item); } }); return result; } // 数组反查法 function removeRepeat(arr) { var result = []; for (var i = 0; i < arr.length; i++) { if (!~result.indexOf(arr[i])) { result.push(arr[i]); } } return result; } // 过滤法 function removeRepeat(arr) { return arr.filter(function(item, idx, array) { return array.indexOf(item) === idx; }); } // ES6 Set 去重法 function removeRepeat(arr) { return [...new Set(arr)]; } // 执行效率排行(从高到低): // 对象属性法 > ES6 Set 去重法 > 数组反查法 > 过滤法 > 指针查询法
本期优秀回答者: @AMY-Y
The text was updated successfully, but these errors were encountered:
//es5 function removeRepeatEs5(arr){ var temp=[]; for(var i=0;i<arr.length;i++){ if(temp.indexOf(arr[i])==-1){ temp.push(arr[i]) } } return temp; } //es6 var removeRepeatEs6=(arr)=>{ return Array.from(new Set(arr)); } var array=[1,1,'1','1',NaN,NaN,null,null,'a',undefined,undefined]; removeRepeatEs5(array);//无法对NaN去重 removeRepeatEs6(array);//可对NaN去重
Sorry, something went wrong.
No branches or pull requests
请编写一个数组去重函数(用 ES5、ES6 各写一个)
参考答案:
本期优秀回答者: @AMY-Y
The text was updated successfully, but these errors were encountered: