Skip to content

数组的 pop push unshift shift 分别是什么

数组的 pop push unshift shift

  • 功能是什么?
  • 返回值是什么?
  • 是否对原数组造成影响?
js
const arr = [10, 20, 30, 40];
// pop
const popRes = arr.pop();
console.log(popRes, arr); // 40 [10, 20, 30]
// shift
const shiftRes = arr.shift();
console.log(shiftRes, arr); // 10 [20, 30, 40]
// push
const pushRes = arr.push(50); // 返回 length
console.log(pushRes, arr); // 5 [10, 20, 30, 40, 50]
// unshift
const unshiftRes = arr.unshift(5); // 返回 length
console.log(unshiftRes, arr); // 5 [5, 10, 20, 30, 40]

数据的 API,有哪些是纯函数?(纯函数:1、不改变原数组;2、返回一个数组)

js
// 纯函数:1、不改变原数组(没有副作用);2、返回一个数组
const arr = [10, 20, 30, 40];
// concat
const arr1 = arr.concat([50, 60, 70]);
console.log(arr, arr1); // [10, 20, 30, 40] [10, 20, 30, 40, 50, 60, 70]
// map
const arr2 = arr.map((num) => num * 10);
console.log(arr, arr2); // [10, 20, 30, 40] [100, 200, 300, 400]
// filter
const arr3 = arr.filter((num) => num > 25);
console.log(arr, arr3); // [10, 20, 30, 40] [30, 40]
// slice
const arr4 = arr.slice(1);
console.log(arr, arr4); // [10, 20, 30, 40]  [20, 30, 40]

非纯函数:push pop shift unshift forEach some every reduce

基于 MIT 许可发布