标签:== for ons new indexof console key div length
var a = [5,6,5,4,‘3‘,{},3,‘字符‘]
方法一:建立新数组,利用indexOf判断是否存在于新数组中,不存在则push到新数组,最后返回新数组
function unique0() { let arr = []; for(let i = 0;len = a.length,i < len;i ++){ if(arr.indexOf(a[i]) === -1){ arr.push(a[i]) } } return arr } console.log(unique0(a))
方法二:利用object对象保存数组值,判断数组值是否已经保存在object中,未保存则push到新数组并用object[arrayItem]=1的方式记录保存
function unique1(a) { let ret = []; let hash = {}; for(let i = 0;len = a.length,i < len ;i ++){ let key = typeof a[i] + a[i] if(!hash[key]){ hash[key] = 1; ret.push(a[i]) } } return ret } console.log(unique1(a))
方法三:ES6新数据结构set,新方法Array.from
function unique2(a) { let arr = new Set(a) return Array.from(arr) } console.log(unique2(a))
标签:== for ons new indexof console key div length
原文地址:http://www.cnblogs.com/kaw19950302/p/7867467.html