数组实例方法
push
const arr = ['苹果','华为','三星']
const pushArr = arr.push('小米')
console.log(pushArr)
console.log(arr)
pop
const arr = ['苹果','华为','三星']
const popArr = arr.pop();
console.log(arr);
console.log(popArr);
unshift
const arr = ['苹果','华为','三星']
const unshiftArr = arr.unshilt('小米')
console.log(arr)
console.log(unshiltArr)
shift
const arr = ['苹果','华为','三星']
const shiftArr = arr.shift()
console.log(arr)
console.log(shiftArr)
slice
const arr = ['苹果','华为','三星','小米']
const spliceArr = arr.slice()
console.log(arr)
console.log(spliceArr)
const arr1 = ['苹果','华为','三星','小米']
const sliceArr1 = arr1.slice(1);
console.log(arr1)
console.log(sliceArr1)
const arr2 = ['苹果','华为','三星','小米']
const sliceArr2 = arr2.slice(1,3);
console.log(arr2)
console.log(sliceArr2)
splice
const arr1 = ['苹果','华为','三星','联想']
const spliceArr1 = arr1.splice(1,2)
console.log(arr1)
console.log(spliceArr1)
const arr2 = ['苹果','华为','三星','联想']
const spliceArr2 = arr2.splice(1,1,'小米')
console.log(arr2)
console.log(spliceArr2)
const arr3 = ['苹果','华为','三星','联想']
const spliceArr3 = arr3.splice(1,0,'小米')
console.log(arr3)
console.log(spliceArr3)
concat
const arr1 = ['苹果','华为']
const arr2 = ['三星','联想']
const concatArr1 = arr1.concat()
console.log(concatArr1)
const concatArr2 = arr1.concat(arr2,concatArr1)
console.log(concatArr2)
const concatArr3 = arr1.concat(concatArr1,arr2,'小米')
console.log(concatArr3)
join
const arr = ['苹果','华为','小米']
const joinArr1 = arr.join()
console.log(joinArr1)
const joinArr2 = arr.join('-')
console.log(joinArr2)
const joinArr3 = arr.join(`${' | '}`);
console.log(joinArr3)
reverse
const arr = ['苹果','华为','小米']
const reverseArr = arr.reverse()
console.log(arr)
console.log(reverseArr)
sort
const arr = ['苹果','华为','小米']
const sortArr = arr.sort()
console.log(arr)
console.log(sortArr)
const arr1 = ['20','12','21','4','3']
const sortArr1 = arr1.sort(( a , b ) => a - b )
console.log(arr1)
console.log(sortArr1)
const arr2 = ['20','12','21','4','3']
const sortArr2 = arr2.sort(( a , b ) => b - a )
console.log(arr2)
console.log(sortArr2)
const people = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 30 }
]
people.sort((a, b) => a.age - b.age)
console.log(people)
map
const people = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 30 }
]
const mapArr = people.map((item,index,array) => item.name)
console.log(mapArr)
const person = {
name: 'Alice',
sayHello: function() {
return this.name + ', says hello!'
}
}
const greetings = ['Good morning', 'Good afternoon', 'Good night']
const personGreetings = greetings.map(person.sayHello, person)
console.log(personGreetings)
forEach
const people = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 22 },
{ name: 'Doe', age: 30 }
]
const arr = []
people.forEach((item,index,array) => arr.push(item.name))
console.log(arr)
const numArr = [1,22,3,4,5]
numArr.forEach((item,index)=>numArr[index] = item * 2)
console.log(numArr)
const person = {
name: 'Alice',
sayHello: function() {
console.log(this.name + ', says hello!');
}
}
const greetings = ['Good morning', 'Good afternoon', 'Good night']
greetings.forEach(person.sayHello, person)
includes
const numbers = [1, 2, 3, 4, 5];
const res = numbers.includes(3)
console.log(numbers)
console.log(res)
const objArr = [{ id: 1, name: '张三' }, { id: 2, name: '李四' }]
const res2 = objArr.includes({ id: 1, name: '张三' })
console.log(objArr)
console.log(res2)
const objArr1 = [{ id: 1, name: '张三' }, { id: 2, name: '李四' }]
const res3 = objArr1.some(item => item.id === 1 && item.name === '张三');
console.log(res3)
some
const arr = [1, 2, 3, 4, 5]
const res = arr.some(item => item > 3)
console.log(arr)
console.log(res)
const objArr = [
{ name: '张三', age: 18 },
{ name: '李四', age: 20 },
{ name: '王五', age: 22 }
]
const res2 = objArr.some(item => item.age > 20)
console.log(objArr)
console.log(res2)
const hasArr = ['a', 'b', 'c']
const res3 = hasArr.some(item => item === 'd')
console.log(hasArr)
console.log(res3)
const mapSomeArr = [1, 2, 3, 4, 5]
const res4 = mapSomeArr.map(m => m * 2).some(item => item === 8)
console.log(mapSomeArr)
console.log(res4)
every
const arr = []
const res0 = arr.every(()=>false)
const res01 = arr.every(()=>true)
const res03 = arr.every(item => item > 0)
console.log(res0)
console.log(res01)
console.log(res03)
const numbers = [2, 4, 6, 8]
const res = numbers.every(num => num > 0)
console.log(numbers)
console.log(res)
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
const res1 = people.every(person => person.age >= 18)
console.log(res1)
const uniqueIds = [1, 2, 3, 4]
const allUnique = uniqueIds.every((value, index, self) => self.indexOf(value) === index)
console.log(allUnique)
const mainArray = [1, 2, 3, 4, 5]
const subArray = [1, 3, 5]
const allInMainArray = subArray.every(element => mainArray.includes(element))
console.log(allInMainArray)
filter
const arr = [1, undefined, 2, null, 3]
const filtered = arr.filter(item => item === null || item === undefined)
console.log(filtered)
const numbers = [1, 2, 3,null, 4, 5, 6]
const evenNumbers = numbers.filter(num => num % 2 === 0)
console.log(evenNumbers)
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
]
const adults = people.filter(person => person.age >= 28)
console.log(adults)
const items = [1, 2, 2, 3, 4, 4, 5]
const uniqueItems = items.filter((item, index, self) => self.indexOf(item) === index)
console.log(uniqueItems)
find
const arr = [1, 2, 3, null, 9, 10]
const res = arr.find(item => item > 5)
console.log(res)
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
]
const alice = people.find(person => person.name === 'Alice')
console.log(alice)
findIndex
const numbers = [1, 3, 5, 8, 10]
const indexFirstEven = numbers.findIndex(num => num % 2 === 0)
console.log(indexFirstEven)
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
]
const indexAlice = people.findIndex(person => person.name === 'Alice')
console.log(indexAlice)
findLast
const arr = [1, 2, 3, null, 9, 10]
const res = arr.findLast(item => item > 5)
console.log(res)
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 },
{ name: 'Alice', age: 35 }
]
const alice = people.findLast(person => person.name === 'Alice')
console.log(alice)
findLastIndex
const numbers = [1, 3, 5, 8, 10]
const indexFirstEven = numbers.findLastIndex(num => num % 2 === 0)
console.log(indexFirstEven)
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 },
{ name: 'Alice', age: 35 }
]
const indexAlice = people.findLastIndex(person => person.name === 'Alice')
console.log(indexAlice)
reduce
const arr = [1, 2, , 3, undefined, null, 4, 5]
const sum = arr.reduce((accumulator, currentValue) => {
console.log(currentValue)
return accumulator + currentValue
}, 0)
console.log(sum)
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1
return acc
}, {})
console.log(count)
const numbers = [10, 20, 30, 40, 50]
const max = numbers.reduce((maxValue, current) => Math.max(maxValue, current), numbers[0])
console.log(max)
const nestedNumbers = [1, [2, 3], [4, [5, 6]]]
const flatArray = nestedNumbers.reduce((acc, val) =>
acc.concat(Array.isArray(val) ? val.flat() : val), [])
console.log(flatArray)
const keyValuePairs = [['a', 1], ['b', 2], ['c', 3]]
const object = keyValuePairs.reduce((obj, [key, value]) => {
obj[key] = value
return obj
}, {})
console.log(object)
reduceRight
const arr = [1, 2, , 3, undefined, null, 4, 5]
const sum = arr.reduceRight((accumulator, currentValue) => {
console.log(currentValue)
return accumulator + currentValue
}, 0)
console.log(sum)
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
const count = fruits.reduceRight((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1
return acc
}, {})
console.log(count)
const numbers = [10, 20, 30, 40, 50]
const max = numbers.reduceRight((maxValue, current) => Math.max(maxValue, current), numbers[0])
console.log(max)
const nestedNumbers = [1, [2, 3], [4, [5, 6]]]
const flatArray = nestedNumbers.reduceRight((acc, val) =>
acc.concat(Array.isArray(val) ? val.flat() : val), [])
console.log(flatArray)
const keyValuePairs = [['a', 1], ['b', 2], ['c', 3]]
const object = keyValuePairs.reduceRight((obj, [key, value]) => {
obj[key] = value
return obj
}, {})
console.log(object)
indexOf
const numbers = [1, 2, 3, 4, 5]
const index = numbers.indexOf(3)
console.log(index)
const arr = [1, 2, 3, 4, 5,3]
const res = arr.indexOf(3 ,4)
console.log(res)
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
const objIndex = people.indexOf(person => person.name === 'Bob')
console.log(objIndex)
lastIndexOf
const numbers = [1, 2, 3, 4, 2, 5]
const index = numbers.lastIndexOf(3)
console.log(index)
const arr = [1, 2, 3, 4, 2, 5, 3]
const res = arr.lastIndexOf(3, 4)
console.log(res)
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
const objIndex = people.lastIndexOf(person => person.name === 'Bob')
console.log(objIndex)
flat
const nestedArray = [1, [2, 3], 4, [5, [6, 7]]]
const flatArray = nestedArray.flat()
console.log(flatArray)
const deeplyNestedArray = [1, [2, [3, [4, 5]]]]
const flatArray1 = deeplyNestedArray.flat(2)
console.log(flatArray1)
const deeplyNestedArray1 = [1, [2, [3, [4, 5]]]]
const flatArray2 = deeplyNestedArray1.flat(Infinity)
console.log(flatArray2);
flatMap
const numbers = [1, 2, 3]
const doubled = numbers.flatMap(n => [n * 2])
console.log(doubled)
const nestedNumbers = [1, [2, 3], 4]
const flatMapped = nestedNumbers.flatMap(n => Array.isArray(n) ? n : [n])
console.log(flatMapped)
const deeplyNestedNumbers = [1, [2, [3, 4]], 5, [6, [7, [8,9] ] ] ]
const flatMapped1 = deeplyNestedNumbers.flatMap(n =>
Array.isArray(n) ? n.flatMap(n => n) : [n])
console.log(flatMapped1)
copyWithin
const arr = [1, 2, 3, 4, 5]
const res = arr.copyWithin(0, 2)
console.log(arr)
console.log(res)
const arr1 = [1, 2, 3, 4, 5]
arr1.copyWithin(0, 3, 5)
console.log(arr1)
const arr2 = [1, 2, 3, 4, 5]
arr2.copyWithin(0, 2, 5)
console.log(arr2)
const arr3 = [1, 2, 3, 4, 5]
arr3.copyWithin(-3, -5, -2)
console.log(arr3)
toString
const arr = [1, 2, 3, 4]
const res = arr.toString()
console.log(res)
const objArr = [{ name: '张三', age: 18 },{ name: '李四', age: 19 }]
const res1 = objArr.toString()
console.log(res1)
const objArr1 = [{ name: '张三', age: 18 }, { name: '李四', age: 19 }];
const res2 = JSON.stringify(objArr1);
console.log(res2)
toLocaleString
const numbers = [123456.789, 98765.432]
const localeStr = numbers.toLocaleString()
console.log(localeStr)
const dates = [new Date(), new Date()]
const localeStr1 = dates.toLocaleString()
console.log(localeStr1)
const mixed = [123456, new Date()]
const localeStr2 = mixed.toLocaleString()
console.log(localeStr2)
const numbers2 = [123456.789, 98765.432]
const localeStr3 = numbers.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })
console.log(localeStr3)
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
]
const localeStr4 = people.toLocaleString()
console.log(localeStr4)
entries
const arr = [10, 20, 30, 40]
console.log(arr.entries())
for (const [index, value] of arr.entries()) {
console.log(`索引: ${index}, 值: ${value}`)
}
const arr1 = [1, 2, 3];
const res = [...arr1.entries()].map(([index, value]) => ({ index, value }))
console.log(res)
const arr2 = [1, 2, 3];
const res1 = [...arr2.entries()]
console.log(res1)
keys
const arr = [10, 20, 30]
const keys = [...arr.keys()]
console.log(keys)
const fruits = ['apple', 'banana', 'cherry']
for (const key of fruits.keys()) {
console.log(key)
}
const arr1 = [1, 2, 3]
const res = arr1.keys().map((key, index) => [key, arr1[index]])
console.log(res)
values
const fruits = ['apple', 'banana', 'cherry']
console.log(fruits.values())
for (const fruit of fruits.values()) {
console.log(fruit)
}
const arr = [1, 2, 3, 4]
const iterator = arr.values()
console.log(iterator.next().value)
console.log(iterator.next().value)
const numbers = [1, 2, 3]
const values = Array.from(numbers.values())
console.log(values)
at
const arr = [1, 2, 3, 4, 5]
const first = arr.at(0)
const last = arr.at(-1)
console.log(first, last)
const secondLast = numbers.at(-2);
console.log(secondLast);
const element = arr.at(10);
console.log(element)
数组静态方法
Array.isArray
const arr = [1, 2, 3]
console.log(Array.isArray(arr))
const str = 'hello'
console.log(Array.isArray(str))
Array.of
const arr = Array.of()
console.log(arr)
const arr1 = Array.of(42)
console.log(arr1)
const arr2 = Array.of(1, 'two', true, null, undefined, { key: 'value' }, [1, 2, 3])
console.log(arr2)
Array.from
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }
const array = Array.from(arrayLike)
console.log(array)
const str = 'hello'
const charArray = Array.from(str)
console.log(charArray)
const set = new Set(['a', 'b', 'c'])
const arrayFromSet = Array.from(set)
console.log(arrayFromSet)
const map = new Map([[1, 'one'], [2, 'two']])
const arrayFromMapKeys = Array.from(map.keys())
console.log(arrayFromMapKeys)
const numbers = [1, 2, 3, 4, 5]
const doubled = Array.from(numbers, n => n * 2)
console.log(doubled)
const obj = {
multiplyByTwo: function (n) {
return n * 2
}
}
const arr = [1, 2, 3, 4, 5]
const doubled1 = Array.from(arr, obj.multiplyByTwo, obj)
console.log(doubled1)
const filledArray = Array.from({ length : 5 }, (_, index) => index)
console.log(filledArray);
生成数组的方法
const arr1 = [1, 2, 3];
const arr2 = new Array(1, 2, 3);
const arr3 = Array.of(1, 2, 3);
const arr4 = Array.from({ length: 5 }, (_, i) => i + 1);
const str = 'hello';
const arr5 = Array.from(str);
const arr6 = [...'hello'];
const arr7 = new Array(5).fill(0);
const arr8 = Array.from({ length: 5 }, () => Math.random());
const arr9 = Array.from({ length: 5 }, (_, i) => i * 2);
const arr01 = Array.from({ length: 5 }, Number.call, Number);
const arr02 = Array.from({ length: 5 }, Function.call, Number);
const arr03 = Array.from({ length: 5 }, Array.prototype.map, [i => i * 2]);
const arr04 = Array.from({ length: 5 }, Function.apply, [Number, []]);
const arr05 = Array.from({ length: 5 }, Function.bind.call(Number, undefined));
判断数组的方法
console.log ( Array.isArray([1,2,3]))
console.log ( typeof [1,2,3])
console.log( [1,2,3] instanceof Array)
console.log(Array.prototype.isPrototypeOf([1,2,3]))
console.log(Object.prototype.toString.call([1,2,3]) === '[object Array]')
console.log([1,2,3].constructor === Array)
数组的解构赋值
const a = 1
const b = 2
const c = 3
const [a,b,c] = [1,2,3]
const [a] = []
console.log(a)
const [a,b] = [1,2,3]
console.log(a,b)
const [a,,c] = [1,2,3]
console.log(a,c)
const [a,b,c] = [1,2]
console.log(a,b,c)
const [a,[b],c] = [1,[2,3],4]
console.log(a,b,c)
const [a,...b] = [1,2,3,4,5]
console.log(a,b)
const [a,b,...c] = [1]
console.log(a,b,c)
const [a,b=2,c] = [1]
console.log(a,b,c)
const [a,b=2,c] = [1,undefined,3]
console.log(a,b,c)
const [a,b=2,c] = [1,null,3]
console.log(a,b,c)
const [x = 1, y = x] = [];
const [x = 1, y = x] = [2];
const [x = 1, y = x] = [1, 2];
const [x = y, y = 1] = [];
function add([x,y]){
console.log(x+y)
}
add([1,2,3])