【JS】数组

数组:(Array)是一种可以按顺序保存数据的数据类型

数组的基本使用:

1、声明数组

        1、字面量声明数组

let arr = [数据1 , 数据2 , 数据3 ,···, 数据n ]

        2、使用new Array 构造函数声明

let arr = new Array(数据1 , 数据2 ,···, 数据n)

2、取值语法

数组名[下标]

3、遍历数组

for (let i=0 ; i<arr.length ; i++){
    数组名[i]
}

4、操作数组

修改数组

新增数组

        数组.push() 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度

const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

数组筛选

        遍历旧数组,追加到新数组

数组删除

        arr.pop() 方法从数组中删除最后一个元素,并返回该元素的值

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// Expected output: "tomato"

console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage"]

        arr.shift()方法从数组中删除第一个元素,并返回该元素的值

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// Expected output: Array [2, 3]

console.log(firstElement);
// Expected output: 1

        arr.splice(删除的起始下标,删除的个数,需要替换的词) 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。

                如果没有写删除个数,则默认删除到最后

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]

months.splice(4, 1);
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April"]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值