JS 之 操作 Array 数组

目录

Array - JavaScript | MDN

零. 创建数组

1 - [ ]

2 - new Array( 长度 )

一. 访问数组元素

1 - [索引]

2 - at 

二. 新增|删除 元素

1 - push : 尾部新增

2 - pop : 尾部删除

3 - unshift : 头部新增

4 - shift : 头部删除

5 - splice : 任意位置添加/删除/替换元素

删除

新增 

替换 

三. length属性

1 - 获取长度

2 - 修改长度

四. 数组的遍历 

1 - for循环

2 - for...in

3 - for...of

五. slice : 数组截取

六. 数组合并 

1 - concat

2 - ... 运算符

七. join : 数组变成字符串 

八. 数组中查找元素 

1 - indexOf

2 - includes

3 - find 

4 - 手动实现find函数

5 - findIndex

九.  sort : 数组的排序

十.  reverse : 数组的反转

十一.  数组其他高阶函数使用

1 - forEach

2 - 手动实现forEach函数

3 - filter

4 - map

5 - reduce

十二.  数组的解构

1 - 简单的解构

2 - 解构的严格顺序

3 - 解构的默认值

4 - 解构的剩余内容

十三.  flat


Array - JavaScript | MDN

零. 创建数组

1 - [ ]

const arr = []

const list = ['a','b']

2 - new Array( 长度 )

const arr = new Array()

// 创建长度为1024的数组,并且往里填充数字为100 => 也就是 [ 100,100,100,...1024个 ]
const list = new Array(1024).fill(100)

一. 访问数组元素

1 - [索引]

const names = ["abc", "cba", "nba"]

console.log(names[0]) // abc
console.log(names[names.length - 1]) //nba

2 - at 

const names = ["abc", "cba", "nba"]

console.log(names.at(0)) // abc
console.log(names.at(-1)) // nba

二. 新增|删除 元素

1 - push : 尾部新增

const names = ["abc", "cba"]

names.push("star", "kobe")
console.log(names) // ["abc", "cba","star", "kobe"]

2 - pop : 尾部删除

const names = ["abc", "cba"]

names.pop()
console.log(names) // ["abc"]

3 - unshift : 头部新增

const names = ["abc", "cba"]

names.unshift("star", "kobe")
console.log(names) // ["star", "kobe","abc", "cba"]

4 - shift : 头部删除

const names = ["abc", "cba"]

names.shift()
console.log(names) // ["cba"]

注意 : push/pop 方法运行的比较快,而 shift/unshift 比较慢,都不能链式调用

尾部操作不会影响数组结构,头部操作会导致后续元素的移动

5 - splice : 任意位置添加/删除/替换元素

splice : 可以说是处理数组的利器,它可以做所有事情:添加,删除和替换元素

注意 : 这个方法会修改原数组

  • 参数一: start, 从什么位置开始操作元素
  • 参数二: deleteCount, 删除元素的个数 , 如果为0或者负数表示不删除
  • 参数三: 可以为添加的元素 或者 替换的元素

删除

const names = ["abc", "cba", "nba", "mba", "abcd"]
// 在第一个位置开始,删除两个元素
names.splice(1, 2)
console.log(names) // ["abc", "mba", "abcd"]

新增 

const names = ["abc", "cba", "nba"]

// 在第一个位置开始,增加两个元素,注意删除元素的个数为0
names.splice(1, 0, "star", "kobe")
console.log(names) // ["abc","star", "kobe","cba", "nba"]

替换 

const names = ["abc", "cba", "nba", "mba"]

// 从第一个元素开始,删除两个元素,同时增加元素,删除和增加的元素可以不一样 => 看起来就是替换了
names.splice(1, 2, "star", "kobe", "james")
console.log(names) // ["abc", "star", "kobe", "james", "mba"]

三. length属性

1 - 获取长度

const arr = [1,2,3,4]

console.log(arr.length) // 4

2 - 修改长度

  • 如果我们手动增加一个大于默认length的数值,那么会增加数组的长度
  • 但是如果我们减少它,数组就会被截断
  • 清空数组最简单的方法就是:arr.length = 0
const names = ['abc', 'cba', 'nba', 'mba'];

// 设置的length大于原来的元素个数
names.length = 10;
console.log(names); // ["abc", "cba", "nba", "mba",empty × 6]

// 设置的length小于原来的元素个数
names.length = 2
console.log(names) // ['abc', 'cba']

四. 数组的遍历 

1 - for循环

const names = ['abc', 'cba', 'nba', 'mba'];

for (var i = 0; i < names.length; i++) {
  console.log(names[i])
}

2 - for...in

const names = ['abc', 'cba', 'nba', 'mba'];
// index => 索引
for (var index in names) {
  console.log(index, names[index])
}

3 - for...of

const names = ['abc', 'cba', 'nba', 'mba'];
// item => 值
for (var item of names) {
  console.log(item)
}

五. slice : 数组截取

const names = ["abc", "cba", "nba", "mba", "why", "kobe"]

// slice方法: 不会修改原数组
// splice有区别: splice修改原有的数组
// start 从什么位置开始
// end 结束位置, 不包含end本身
const newNames = names.slice(2, 4)
console.log(newNames) // ["nba", "mba"]

六. 数组合并 

1 - concat

const names1 = ["abc", "cba"]
const names2 = ["nba", "mba"]
const names3 = ["why", "kobe"]

const newNames2 = names1.concat(names2, names3)
console.log(newNames2)

2 - ... 运算符

const names1 = ["abc", "cba"]
const names2 = ["nba", "mba"]
const names3 = ["why", "kobe"]

names1.push(...names2, ...names3)

七. join : 数组变成字符串 

const names = ["abc", "cba", "nba", "mba", "why", "kobe"]

console.log(names.join("-")) // "abc-cba-nba-mba-why-kobe"

八. 数组中查找元素 

1 - indexOf

const names = ["abc", "cba", "nba", "mba"]

// 可以找到, 返回对应的索引
// 没有找到, 返回-1
console.log(names.indexOf("nbb")) // -1

2 - includes

const names = ["abc", "cba", "nba", "mba"]

console.log(names.includes("cba")) // true
console.log(names.includes("nbb")) // false

3 - find 

const students = [
  { id: 100, name: "why", age: 18 },
  { id: 101, name: "kobe", age: 30 },
  { id: 102, name: "james", age: 25 },
  { id: 103, name: "why", age: 22 }
]

// 有多少项,就会执行多少次find函数,执行的时候会把当前项的值,索引,数组传递过来
const stu = students.find(function(item,index,arr) {
  console.log(item,index,arr)
  // 当返回的值不为空的时候,意味着找到了,会停止查找,返回当前项
  if (item.id === 101) return true
})

//可使用箭头函数简便写法
const stu1 = students.find(item => item.id === 101)

4 - 手动实现find函数

const names = [
  { id: 100, name: 'why', age: 18 },
  { id: 101, name: 'kobe', age: 30 },
  { id: 102, name: 'james', age: 25 },
  { id: 103, name: 'why', age: 22 }
];
// 把该方法绑定到数组原型上面. 可指定this
Array.prototype.starFind = function (fn,thisArgs) {
  let bool = false;
  for (let i = 0; i < this.length; i++) {
    // 接受返回的bool值
    bool = fn.call(thisArgs, this[i], i, this);
    // 如果返回true,说明找到了
    if (bool) {
      // 把找到的该项的值返回出去
      return this[i];
    }
  }
  // 如果没有找到,会默认返回undefined
};
// 可直接调用,同时接受返回的值
const findValues = names.starFind((item, index, arr) => {
  return item.id === 102;
},{});
console.log(findValues); // { id: 102, name: 'james', age: 25 }

5 - findIndex

const names = ["abc", "cba", "nba"]

// 和find方法类似,不过这里是返回查找项的索引值
const findIndex = names.findIndex(function(item, index, arr) {
  return item === "nba"
})

// 简便写法
var findIndex1 = names.findIndex(item => item === "nba")

九.  sort : 数组的排序

是一个高阶函数,用于对数组进行排序,并且生成一个排序后的新数组

  • 如果 compareFunction(a, b) 小于 0 ,那么 a 会被排列到 b 前面
  • 如果 compareFunction(a, b) 等于 0 , a 和 b 的相对位置不变
  • 如果 compareFunction(a, b) 大于 0 , b 会被排列到 a 前面
  • 也就是说,谁小谁排在 前面
const nums = [20, 4, 10, 15, 100, 88]
// sort: 排序
nums.sort(function(item1, item2) {
  // 升序
  return item1 - item2 // [4,10,15,20,88,100]
  // 降序
  // return item2 - item1
})

// --------------------------------------------

const students = [
  { id: 100, name: "why", age: 18 },
  { id: 101, name: "kobe", age: 30 },
  { id: 102, name: "james", age: 25 },
  { id: 103, name: "curry", age: 22 }
]

students.sort(function(item1, item2) {
  return item1.age - item2.age
})
console.log(students)

十.  reverse : 数组的反转

<script>
  const arr = ['a', 'b', 'c'];
  console.log(arr.reverse()); // ['c', 'b', 'a']

  const list = [1, 4, 2, 5];
  console.log(list.reverse()); // [5, 2, 4, 1]
</script>

十一.  数组其他高阶函数使用

1 - forEach

const names = ['avbc', 'fggd', 'eerw'];

// 可取出数组中的每一项的值,索引,数组本身
// 第二个参数,传入指定的this对象
names.forEach(function (item, index, names) {
  console.log(item, index, names, this);
}, {});

2 - 手动实现forEach函数

const names = ['abc', 'abvc', 'aser'];
// 把该方法绑定到数组原型上面
Array.prototype.starForEach = function (fn,thisArgs) {
  // this指向调用该函数的对象,names调用,所以指向names数组
  for (let i = 0; i < this.length; i++) {
    fn.call(thisArgs, this[i], i, this);
  }
};
// 可直接调用
names.starForEach((item, index, arr) => {
  console.log(item, index, arr);
},{});

3 - filter

const nums = [11, 20, 55, 100, 88, 32];

// 过滤数据,符合条件的会push到内部的数组中,最后一起返回出去
const newNums = nums.filter(function (item) {
  return item % 2 === 0;
});
console.log(newNums); // [20,100,88,32]


// filter 不会便利 undefined 的值

const arr = [0, 1, 2];
arr[10] = 10;

console.log(...arr); // 0 1 2 undefined undefined undefined undefined undefined undefined undefined 10

const res = arr.filter(function (x) {
  console.log('x', x); // 0 1 2 10    没有undefined
});

4 - map

const nums = [11, 20, 55, 100, 88, 32]
// map => 映射 , 返回操作后的数据保存在新数组中,最后一起返回出去
const newNums = nums.map(function(item) {
  return item * item
})
console.log(newNums)

5 - reduce

const nums = [11, 20, 55, 100, 88, 32]
// 第一次执行: preValue->0 item->11
// 第二次执行: preValue->11 item->20
// 第三次执行: preValue->31 item->55
// 第四次执行: preValue->86 item->100
// 第五次执行: preValue->186 item->88
// 第六次执行: preValue->274 item->32
// 最后一次执行的时候 preValue + item, 它会作为reduce的返回值

// initialValue: 初始化值, 第一次执行的时候, 对应的preValue

// 如果initialValue没有传,第一次的时候preValue = 11  item = 12
const result = nums.reduce(function(preValue, item) {
  console.log(`preValue:${preValue} item:${item}`)
  return preValue + item
}, 0)
console.log(result)

十二.  数组的解构

1 - 简单的解构

const names = ['abc', 'cba', 'nba', 'mba'];
// 解构
const [name1, name2, name3] = names

console.log(name1, name2, name3) // abc cba nba

2 - 解构的严格顺序

const names = ['abc', 'cba', 'nba', 'mba'];

// 如果不要第二个顺序,留一个空的位置
const [name1, , name3] = names
console.log(name1, name3) // abc nba

3 - 解构的默认值

const names = ['abc', 'cba', undefined, 'nba', 'mba'];

// 值为undefined的会使用默认值,本身有值的不会使用默认值
const [name1, name2 = "default", name3 = "default"] = names

console.log(name1, name2, name3) // abc cba default

4 - 解构的剩余内容

const names = ['abc', 'cba', 'nba', 'mba'];

// 剩余没解构的数据会放入newNames数组中
const [name1, name2, ...newNames] = names
console.log(name1, name2) // abc cba
console.log(newNames) // ['nba', 'mba']

十三.  flat

flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回

就是扁平化,让数组处在同一级别

// 将一个数组, 按照制定的深度遍历, 将遍历到的元素和子数组中的元素组成一个新的数组, 进行返回
const nums = [
  10,
  20,
  [111, 222],
  [333, 444],
  [
    [123, 321],
    [231, 312]
  ]
];

// 平了第一层
const newNums1 = nums.flat(1);
console.log(newNums1); // [10, 20, 111, 222, 333, 444, Array(2), Array(2)]

// 平了两层
const newNums2 = nums.flat(2);
console.log(newNums2); // [10, 20, 111, 222, 333, 444, 123, 321, 231, 312]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript中的数组方法用于对数组进行各种操作和转换。下面是一些常见的数组方法: 1. push():将一个或多个元素添加到数组的末尾。 2. pop():移除并返回数组的最后一个元素。 3. shift():移除并返回数组的第一个元素。 4. unshift():将一个或多个元素添加到数组的开头。 5. concat():将两个或多个数组合并为一个新数组。 6. slice():返回选定数组的一部分,不修改原始数组。 7. splice():从数组中添加、删除或替换元素。 8. indexOf():返回指定元素在数组中的第一个匹配位置的索引。 9. lastIndexOf():返回指定元素在数组中最后一个匹配位置的索引。 10. forEach():对数组的每个元素执行提供的函数。 11. map():对数组的每个元素执行提供的函数,并返回新数组。 12. filter():根据指定的条件筛选数组元素,并返回一个新数组。 13. reduce():从左到右对数组的每个元素执行提供的函数,以将其减少为单个值。 14. reduceRight():从右到左对数组的每个元素执行提供的函数,以将其减少为单个值。 15. sort():对数组的元素进行排序。 16. reverse():颠倒数组的元素顺序。 17. join():将数组的所有元素连接成一个字符串。 18. includes():判断数组是否包含某个元素。 19. every():判断数组的每个元素是否都满足指定条件。 20. some():判断数组的某个元素是否满足指定条件。 以上是一些常见的数组方法。你可以根据需要选择适合的方法来操作和处理数组

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值