JavaScript數組循環遍歷總結

這一部分應該放在《JavaScript處理數組函數總結》裏面的,可是。。。。。。沒有可是。javascript

1. for

for循環最經常使用的地方是利用索引來遍歷數組:html

var arr = ['Microsoft','Google','Apple','BUPT'];
var x,i;
for (i=0; i<arr.length; i++){
    //do something
    console.log(arr[i]);
}

2.for...in

for循環的一個變體是for ... in循環,它能夠把一個對象的全部屬性依次循環出來:java

var arr = [10,20,30];
for (var i in arr){
    console.log(i+' : '+typeof i);//0 : string
    console.log(arr[i]+' : '+typeof arr[i]);//10 : number
}

注意:segmentfault

  • for ... in 是用來遍歷對象的屬性的,實際上JavaScript對象的全部屬性都是字符串,不過屬性對應的值能夠是任意數據類型。數組

  • 因爲Array也是對象,而它的每一個元素的索引被視爲對象的屬性,所以,for ... in循環能夠直接循環出Array的索引,但獲得的是String而不是Number函數

3. forEach()

forEach 從頭至尾遍歷數組,爲每一個元素調用制定的函數測試

function say(element, index, array){
    document.write('['+index+'] is '+element);
}
['one','two','three'].forEach(say);//[0] is one...

補充:網站

arrayObject.forEach(callback[, thisObject])this

callback: 函數測試數組的每一個元素
thisObject: 對象做爲該執行回調時使用.net

  • 兼容性問題:forEach是一個JavaScript擴展到ECMA-262標準;所以它可能不存在在標準的其餘實現。好比,FirefoxChromeArray 類型都有forEach的函數,可是IE中中沒有。

  • 兼容IE的方法:添加以下腳本

//Array.forEach implementation for IE support..
//https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(callback, thisArg) {
        var T, k;
        if (this == null) {
            throw new TypeError(" this is null or not defined");
        }
        var O = Object(this);
        var len = O.length >>> 0; // Hack to convert O.length to a UInt32
        if ({}.toString.call(callback) != "[object Function]") {
            throw new TypeError(callback + " is not a function");
        }
        if (thisArg) {
            T = thisArg;
        }
        k = 0;
        while (k < len) {
            var kValue;
            if (k in O) {
                kValue = O[k];
                callback.call(T, kValue, k, O);
            }
            k++;
        }
    };
}

引伸:forEach實現的數組去重函數:

Array.prototype.delrep = function(fun){

    if (this === null){
            throw new TypeError('this is null or not defined');
    }
    if (!fun){
        function fun(d){
            return d ;
        }
    } else {
        if (Object.prototype.toString.call(fun) != '[object Function]'){
            throw new TypeError(fun +'is not a function');
        }
    }
    
    var newArr = [];
    this.sort(function(a,b){
        return fun(a) > fun(b)? -1 : 1;
    });
    newArr.push(this[0]);
    this.forEach(function(d){
        if (fun(d) != fun(newArr[0])){
            newArr.unshift(d);
        }
    });
    return newArr;    
}

//測試實例1
[5,2,6,3,5,3,6,7,4].delrep();//[2,3,4,5,6,7]

data = [
    {
        name : 'hihi',
        value: 123
    },
    {
        name : 'guagua',
        value: 345
    },
    {
        name : 'hihi',
        value: 567
    }
]
data.delrep(function(d){
    return d.name;
}); /* [
    {
        name : 'hihi',
        value: 123
    },
    {
        name : 'guagua',
        value: 345
    },
    {
        name : 'hihi',
        value: 567
    }
] */

4.map

map 把數組的每一個元素傳給指定的函數,並返回一個數組。

function pow(x){
    return x*x;
}
[1,2,3,4].map(pow);//[1,4,9,16]

5.reduce

Arrayreduce()把一個函數做用在這個Array[x1, x2, x3...]上,這個函數必須接收兩個參數,reduce()把結果繼續和序列的下一個元素作累積計算,其效果就是:

[x1,x2,x3,x4].reduce(f) = f(x4,f(x3,f(x1,x2)))
var arr = [1,2,3,4,5];
arr.reduce(function(a,b){
    return a*10+b;
});//12345

6.filter

filter 把數組的每一個元素傳給指定的函數,經過函數返回的布爾值決定是否在返回數組中添加該元素

var arr = [' A','',undefined,null,' ','c'];
var r = arr.filter(function(s){
    return s&&s.trim();// 注意:IE9如下的版本沒有trim()方法
});
arr;//['A','',undefined,null,' ','c']
r;//['A','C']

注意:filter會返回一個新數組

7.every

肯定數組的全部成員是否知足指定的測試。

arrayObject.every(callback[, thisArg])

callback: 必需。一個接受最多三個參數的函數。 every 方法會爲 arrayObject 中的每一個元素調用 callback 函數,直到 callback 返回 false,或直到到達數組的結尾。
thisArg: 可選。可在 callback 函數中爲其引用 this 關鍵字的對象。若是省略 thisArg,則 undefined 將用做 this

  • 返回值: 若是 callback 函數爲全部數組元素返回 true,則爲 true;不然爲 false。若是數組沒有元素,則 every 方法將返回 true

注意:

  • every 方法會按升序順序對每一個數組元素調用一次 callback 函數,直到 callback 函數返回 false。若是找到致使 callback 返回 false 的元素,則 every 方法會當即返回 false。不然,every 方法返回 true

  • 不爲數組中缺乏的元素調用該回調函數。

  • 除了數組對象以外,every 方法可由具備 length 屬性且具備已按數字編制索引的屬性名的任何對象使用。

  • 回調函數語法

function callback(value,index,array)
可以使用最多三個參數來聲明回調函數。

value:數組元素的值。
index:數組元素的數字索引。
array:包含該元素的數組對象。

// Create a function that returns true if the value is
// numeric and within range.
var checkNumericRange = function(value) {
    if (typeof value !== 'number')
        return false;
    else 
        return value >= this.minimum && value <= this.maximum;
}

// Create an array of numbers.
var numbers = [10, 15, 19];

// Check whether the callback function returns true for
// all of the array values.
// The obj argument enables use of the this value
// within the callback function.

var obj = { minimum: 10, maximum: 20 }

if (numbers.every(checkNumericRange, obj))
    document.write ("All are within range.");
else
    document.write ("Some are not within range.");

// Output:
//   All are within range.

8.some

some方法和every方法的語法相似,不過some方法把數組的每一個元素傳給指定的函數,若是有調用返回trueevery函數返回true

arrayObject.some(callback[, thisArg])

callback: 必需。一個接受最多三個參數的函數。 every 方法會爲 arrayObject 中的每一個元素調用 callback 函數,直到 callback 返回 true,或直到到達數組的結尾。
thisArg: 可選。可在 callback 函數中爲其引用 this 關鍵字的對象。若是省略 thisArg,則 undefined 將用做 this

  • 返回值: some 方法會按升序索引順序對每一個數組元素調用 callback 函數,直到 callback 函數返回 true。若是找到致使 callback 返回 true 的元素,則 some 方法會當即返回 true。若是回調不對任何元素返回 true,則 some 方法會返回 false

參考

1.循環-廖雪峯官方網站
2.詳解JavaScript中的forEach()方法的使用
3.javascript的Foreach語法
4.javascript數組去重函數
5.ECMAScript 5中的數組新方法
6.every 方法 (Array) (JavaScript).aspx)

相關文章
相關標籤/搜索