常用的幾個陣列操作方法

李文楊發表於2017-12-08

1.取餘分割陣列

var chartArr = [1, 2, 3, 4, 5, 6, 7];
Array.prototype.splitArray = function(num) {
    var m = this;
    var currData = [];
    var doneData = [];
    for (var i = 0; i < m.length; i++) {
        currData.push(m[i]);
        if (i != 0 && (i + 1) % 4 == 0 || i == m.length - 1) {
            doneData.push(currData);
            currData = [];
        };
    };
    if (doneData.length > 0) {
        return doneData;
    } else {
        return false;
    };
};
var newArr = chartArr.splitArray(4);

2. 陣列去重

Array.prototype.unique = function() {
    var arr = [];
    var obj = {};
    for (var i = 0; i < this.length; i++) {
        if (!obj[this[i]]) {
            arr.push(this[i]);
            obj[this[i]] = i + 1;
        };
    };
    return arr;
};
var arr = [112, 112, 34, '你好', 112, 112, 34, '你好', 'str', 'str1'];
console.log(arr.unique());

3. 陣列反向(其實reverse也可以)

Array.prototype.resore = function() {
var newArr = [];
for (var i = this.length - 1; i >= 0; i--) {
newArr.push(this[i]);
}
return newArr;
};
var res = chartArr.resore();
console.log(res);

4.氣泡排序

var sorArr = [0, 5, 8, 4, 3, 1, 2];
Array.prototype.sortArr = function(arr) {
for (var i = 0; i < arr.length; i++) {
for(var j=i+1;j<arr.length;j++){
var cur = arr[i];
if(cur>arr[j]){
var ind = arr[j];
arr[j] = cur;
arr[i] = ind;
}
};
};
return arr;
};
var sor = sorArr.sortArr(sorArr);
console.log(sor);

相關文章