js 数组遍历

map、filter、forEach、every、some

http://www.runoob.com/jsref/jsref-obj-array.html

1、在字符串中使用 map

在一个String上使用 map 方法获取字符串中每个字符所对应的 ASCII 码组成的数组:

var map = Array.prototype.map
var a = map.call("Hello World", function(x) { return x.charCodeAt(0); })
// a的值为[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

2、JavaScript中 map 函数和 filter 的区别

  • filter 检测数值元素,并返回符合条件所有元素的数组。(对原数组的过滤)
  • map 通过指定函数处理数组的每个元素,并返回处理后的数组。(对原数组的加工)
var arr = [1, 2, 3, 4];
var newArr = arr.filter(function(item) { 
        if (item % 2 !== 0) {
            return item;
        } 
});
console.log(newArr); //[1, 3]
console.log(arr); //[1, 2, 3, 4]

var newArr = arr.map(function(item) {
        if (item % 2 !== 0) {
            return item;
        } 
});
console.log(newArr);//[1, undefined, 3, undefined]
var arr = [1, 2, 3, 4];
var newArr = arr.map(function(item) {
        return item * 2;
});
console.log(newArr);//[2, 4, 6, 8]
console.log(arr);//[1, 2, 3, 4]

3、易犯错误

通常情况下,map 方法中的 callback 函数只需要接受一个参数(很多时候,自定义的函数形参只有一个),就是正在被遍历的数组元素本身。
但这并不意味着 map 只给 callback 传了一个参数(会传递3个参数)。这个思维惯性可能会让我们犯一个很容易犯的错误

// 下面的语句返回什么呢:
["1", "2", "3"].map(parseInt);
// 你可能觉的会是[1, 2, 3]
// 但实际的结果是 [1, NaN, NaN]

// 通常使用parseInt时,只需要传递一个参数.但实际上,parseInt可以有两个参数.第二个参数是进制数.可以通过语句"alert(parseInt.length)===2"来验证.
// map方法在调用callback函数时,会给它传递三个参数:当前正在遍历的元素, 元素索引, 原数组本身.
// 第三个参数parseInt会忽视, 但第二个参数不会,也就是说,parseInt把传过来的索引值当成进制数来使用.从而返回了NaN.
/*
//应该使用如下的用户函数returnInt

function returnInt(element){
  return parseInt(element,10);
}

["1", "2", "3"].map(returnInt);
// 返回[1,2,3]
*/

forEach 无法跳出循环,可使用 Array.everyArray.some

[1,2,3].some(function(i) {
    if(i == 2) return true;
    console.log(i);
});

4、NodeList不是数组

inStorageDateArr.some is not a function

verifyBillingDate: function() {
  var billingDateValue=new Date(document.querySelector("#billingDate").value);
  var inStorageDateArr=document.querySelectorAll(".inStorageDate");
  billingDateMore=inStorageDateArr.some(function(currentValue,index){
      return $.dateDiff("d",new Date(currentValue),billingDateValue)>=0
  });
}

// 用for循环
var inStorageDateList=document.querySelectorAll(".inStorageDate");
for(var i = 0; i < inStorageDateList.length; i++){
    inStorageDateList[i].style.border="1px solid #f30";
}

for in 和 for of

for in (es5)遍历的是数组的索引(即键名)
for of (es6)遍历的是数组元素值

for in适合遍历对象,但是Array也是对象

Array是数组,也是Dictionary,也是Stack

var dict=new Array();//作为Dictionary使用
 
dict['我']='wo';
 
dict['爱']='ai';
 
dict['你']='ni';
 
alert(dict['我']); //通过键值调用
 
alert(dict.爱); //像调用属性一样调用(动态语言的特性)
 
 
for(var k in dict){ //js中的遍历
 alert(k);  //'我','爱','你'-->打印出的是key
}
 
for(var k of dict){ //js中的遍历
 alert(k);  //'wo','ai','ni'-->打印出的是value
}
 
var arr = [1,2,3,4,5];//Array的简化创建方式
 
var arr = {"irving":21,"cloud":20};//字典风格的创建方式
原文地址:https://www.cnblogs.com/papi/p/7115817.html