1. 程式人生 > >數組叠代

數組叠代

func ray 如果 this 滿足 log lte typeof var

var arr = [3,4,5,6,7,"a"];

var isNum = function(elem,index,AAA){
return !isNaN(elem);
}

var toUpperCase = function(elem){
return String.prototype.toUpperCase.apply(elem);
}

var print = function(elem,index){
console.log(index+"."+elem);
}

/*對數組中的每一項執行測試函數,直到獲得對指定的函數返回 false 的項。 使用此方法 可確定數組中的所有項是否滿足某一條件,類似於&&的含義*/
var res = arr.every(isNum);
console.log(res);//false;

/*對數組中的每一項執行測試函數,直到獲得返回 true 的項。 使用此方法確定數組中的所有項是否滿足條件.類似於||的含義*/
res = arr.some(isNum);
console.log(res);//true

/*對數組中的每一項執行測試函數,並構造一個新數組,返回 true的項被添加進新數組。 如果某項返回 false,則新數組中將不包含此項*/
res = arr.filter(isNum);
console.log(res);//[3, 4, 5, 6, 7]

/*對數組中的每一項執行函數並構造一個新數組,並將原始數組中的每一項的函數結添加進新數組。*/
res = arr.map(toUpperCase);
console.log(res);//["3", "4", "5", "6", "7", "A"]

/*對數組中的每一項執行函數,不返回值*/
res = arr.forEach(print);
console.log(res);

//自己擴展

/*Array.prototype.every = function(fun,obj) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
for (var i = 0; i < len; i++) {
if (!fun.call(obj,this[i], i,this))
return false;
}
return true;
};*/

數組叠代