【JavaScript03】Array数组对象基本操作

  • 首先定义一个数组,可以用[];也可以使用new Array() 来创建一个数组对象
  • 数组通过下标取值
      1. 数组通过下标取值,从0开始
      1. 在python中可以通过下标-1反着取倒数第一个值,JavaScript中没这种取值方法.当数组的下标不在它取值范围内,如x有4个成员,那么取值是0-3,非0-3的数字下标取值,得到结果是undefined
var x = ['hello', 'world', true, 12]
// 下标取值, 从0开始
a = x[0]
b = x[1]
console.log(a)  // hello
console.log(b)  // world

c = x[-1]
d = x[6]
console.log(c)  // undefined
console.log(d)  // undefined
  • 给数组元素重新赋值
    • 数组中的成员可以是任意数据类型,数组中的成员是可变的,可以重新赋值
    • 当下标不在x的成员取值0-3的数字
      • 比如我给下标4赋值,那么此时会在数组后面追加一个元素
      • 如果下标跳过4,直接给个6呢?那么此时下标4和5的值会被赋值empty,数组的长度会变成7
    • 如果下标不是一个数字,是一个字符串,那么此时并不会报错,它会称为数组的一个属性,因为数组是一个对象,可以有属性(很少用)
var x = ['hello', 'world', true, 12]
// 下标取值, 从0开始
x[4] = 'aa'
console.log(x) //  ['hello', 'world', true, 12, 'aa']

// 如果下标跳过4,直接给个6呢?
var x = ['hello', 'world', true, 12]
x[6] = '66'
console.log(x) //  ['hello', 'world', true, 12, 空属性 × 2, '66']

// 添加属性,不改变数组长度
var x = ['hello', 'world', true, 12]
x['user'] = 'yoyo'
console.log(x)  // ['hello', 'world', true, 12, user: 'yoyo']
console.log(x.length)     // 4
  • 数组增删成员
// 1. push必须记住, 在右侧添加数据 -> python -> append()
arr.push("周润发");
arr.push("周星驰");
console.log(arr);

// 2. unshift(). 在左侧添加数据.
arr.unshift("马化腾");
arr.unshift("不疼痛");
arr.unshift("很疼");
console.log(arr);

// 删除数据
var arr = [11, 22, 33];
// 1. pop() 必须记住. 刪除的是最右侧的数据
var ret = arr.pop();
console.log(arr);
console.log(ret);

// 2. shift() 从左侧删除数据
var ret = arr.shift();
console.log(arr);
console.log(ret);
  • join 数组拼接成字符串
var x = ['hello', 'world', 'aa'];
console.log(x.join('_'))  // hello_world_aa
  • 数组循环遍历
var arr = [11, 22, 33, 44, 55, 66];

//方法1:最笨的
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[3]);
console.log(arr[4]);

//方法2:通过索引
for (var i = 0 ; i < arr.length; i++){
      console.log(arr[i]);
     }

//方法3:用for-of  ->  python -> for item in lst:
for(var m of arr){
       console.log(m);
    }

//方法4:for-in  -> python -> for i in range(len(lst)):
for(var i in arr){
        console.log(arr[i]);
    }

//方法5:map: 分发. 自动回收返回值
var ret = arr.map(function(item){
        return item + 10;
    });
console.log(ret);  //(6) [21, 32, 43, 54, 65, 76]


//方法6:orEach: 也类似map的操作, 不回收返回值.
var ret = arr.forEach(function(item){
        return item + 10;
    });
console.log(ret);   //undefined

  • 数组常见方法


posted @ 2023-08-06 12:27  Tony_xiao  阅读(21)  评论(0编辑  收藏  举报