数组 数组遍历 多维数组 数组类型转换

37 阅读1分钟

数组

数组 就是将多个元素按一定顺序排列放到一个集合中,这个集合就是数组
实例化创建:var arr = new Array(3); ==> [ , , ]
           var arr = new Array(1,2,3); ==> [1, 2, 3]
字面量创建(常用):var arr = [];
数组的属性:
        arr.length 获取数组长度
        arr.length = 0 自定义 可以大于数组长度,定义新的内容
        arr[0] 取值
        arr[0] = 9 可修改内容

数组遍历

`//有4位嫌疑人 让证人一一辨认 嫌疑人叫王五
var suspects = ['张三', '李四', '王五', '赵六'];
for(var i = 0; i < suspects.length; i++){
  if(suspects[i] === '王五'){
    console.log('就是他:' + i + '号嫌疑人');
  }
}`

for in(有可能出现乱序,不推荐)
    idx是序号 suspects[idx]是序号对应的名字
    `for(var idx in suspects) {
      console.log(idx, suspects[idx]);
    }` 
    
for of
    item是名字
    `for(var item of suspects) {
      console.log(item);
    }`

多维数组

var arr = [[1,2],[3,4]];
获取数组里面第一个数组的2   arr[0][1]

数组类型转换

验证数组类型 1. arr instanceof Array是返回true
            2.Object.prototype.toString.call(arr) 返回【object Array3.Array.isArray(arr)  目前常用的方法 返回值是true 或者 false
            因为typeof 这个方法的返回值是object
Number(arr) 返回NaN
String(arr) 返回'1,2,3'
Boolean(arr) 返回true
[] == [] 返回false  对象和对象永远不相等
运算基本都为NaN,除了 数组中只有1项且能转为数字
arr + []  返回'1,2,3'
!![] 返回true