方法一:
var arr = [1, 1, 1, 3, 2, 3, 3, 4]; console.info(unique(arr)); function unique(arr) { var newArr = [], isReated; for (var i = 0; i < arr.length; i++) { isReated = false; for (var j = 0; j < newArr.length; j++) { if (arr[i] == newArr[j]) { isReated = true; break; } } if (!isReated) { newArr.push(arr[i]); } } return newArr; }
方法二:
function unique(arr) { var newArr = []; for (var i = 0; i < arr.length; i++) { if (arr.indexOf(arr[i]) == i) { newArr.push(arr[i]); } } return newArr; }
方法三:
var arr = [1, 1, 1, 3, 2, 3, 3, 4]; console.info(unique(arr)); function unique(arr) { var newArr = []; for (var i = 0, len = arr.length; i < len; i++) { if (newArr.indexOf(arr[i]) == -1) { newArr.push(arr[i]); } } return newArr; }