JavaScript-配列が重くなります.

1317 ワード

配列
1.forサイクル
var myArray = [1, 2, 3, 4, 5, 2];

function getArray(array) {
    var newArray = [];
    var i = 0, l = array.length
    for (; i < l; i++) {
        for (var j = i + 1; j < l; j++) {
            if (array[i] === array[j]) {
                // i++ ++i   ~~    
                j = ++i;
            }
        }
        newArray.push(array[i]);
    }
    return newArray;
}
console.log(getArray(myArray));
2.0行のコードが少なくなりました.
var arr = [0, 0, 1, 1, 2, 2]
var result = [0, 0, 1, 1, 2, 2].filter((item, index) => arr.indexOf(item) === index)
console.log(result);
3.0 indexOf
function getArray(array){
    var newArray = [];
    for(var i = 0; i < array.length; i++){
        if(newArray.indexOf(array[i]) == -1){
            newArray.push(array[i]);
        }      
    }
    return newArray;
 }
 var myArray = [1,2,3,4,5,2];
 console.log(getArray(myArray));
4.0 map/forEach
var arr = [1,2,3,4,5,2,3,2];
function getArray(arr){
    var newArr = [];
    arr.map(function(item,index,arr){
        if(arr.indexOf(item,index+1) == -1){
            newArr.push(item)
        }
    })
    return newArr;
}
console.log(getArray(arr));
  • ES 6 Set()方法
  • new Set([1,2,3,4,5,2,3,2])