At the beginning of the new year, we will revisit the expansion of ES6 array.
Array extension
1. First briefly review the array method in ES5
Change the of the original array: add to: push / unshift Delete: pop / shift Add or delete anywhere: splice(startIndex,delCount, ...addElement) Flip: reverse Sort: sort Do not change the of the original array: indexOf / lastIndexOf: Only basic types can be retrieved, and complex types (reference types) cannot be retrieved cancat(arr1, arr2, ...) join(str)
Answer: except A
2. Static method
ES5: Array.isArray()
- typeof: can only be used to detect basic types, not reference types
- Function: check whether a variable / data is an array (type)
- Return: if it is an array (type), return true; Otherwise, false is returned
const array = ['Webpack', 'ES6', 'TypeScript', 'React'] const obj = {} console.log(typeof array) //object console.log(typeof obj) //object console.log(Array.isArray(array)) // true console.log(Array.isArray(obj)) // false
ES6: array.from()
- effect:
- Convert a class (false / pseudo) array to a real array,
- If the return function is passed in, you can further process the traversal results,
- The result returned by the return function will be used as the member of the new array
- For example:
- 1.document.querySelectorAll()/document.getElementsByTagName()
- 2.arguments
- return:
- True array after conversion
function fn() { console.log(arguments) // Pseudo array console.log(Array.from(arguments)) // True array let arr = Array.from(arguments, (item, index) => item * 2 ) console.log(arr) // Returns a new array } fn(1, 2, 3, 4, 5, 6)
ES6: array.of()
- Function: convert a pile of scattered data into an array and return
- Return: converted array
console.log(Array.of('scattered', 'array', 'return')) //(3) ['scattered', 'array', 'return']
3. Array instance method
includes(el)
- Function: determine whether the element el is in the array. It is used to replace the indexOf/lastindexOf methods,
In contrast, includes is more semantic and is usually used with if statements - Note: because includes is internally judged by three equal signs, it can only judge basic types,
Reference type cannot be determined - Return: If yes, return true; Otherwise, false is returned
Basic type
const beauty = ['Blademaster', 'Demon God', 'element', 'create'] // indexOf console.log(beauty.indexOf('Demon God')) // 1 console.log(beauty.indexOf('Judo')) // -1 // includes is judged by = = = internally, so it can only be a basic type console.log(beauty.includes('Demon God')) // true console.log(beauty.includes('Judo')) // false
reference type
const boys = [ { name: 'Dungeons', from: 'tencent' } ] console.log( { name: 'Dungeons', from: 'tencent' } === { name: 'Dungeons', from: 'tencent' } ) // false because memory points to different console.log( boys.includes({ name: 'Dungeons', from: 'tencent' }) ) //false
fill()
- Function: replacing / filling the elements of the array with a fixed value will change the original array
- Syntax: array fill(value, startIndex = 0, endIndex = arr.length])
Basic type
const beauty = ['Blademaster', 'Demon God', 'element', 'create'] // replace all console.log(beauty.fill('Dungeons')) // (4) ['dungeons',' dungeons', 'dungeons',' dungeons'] console.log(beauty.includes('Dungeons')) // So it is true // Replace the first two console.log(beauty.fill('Judo', 0, 2)) // (4) ['judo', 'judo', 'dungeons',' dungeons']
reference type
const boys = [ { name: 'Dungeons', from: 'tencent' }, { name: 'Cross Fire', from: 'tencent' } ] boys.fill({ name: 'study', from: 'make progress every day' }) console.log(boys) // Create an array with length of 5 and elements of dungeons console.log(Array(5).fill('Dungeons')) // newly added console.log(new Array('q', 'c', 'm').fill('warrior')) // Replace elements in array // Object form console.log( Array(5).fill({ name: 'study', from: 'make progress every day' }) ) // newly added console.log( new Array('q', 'c', 'm').fill({ name: 'study', from: 'make progress every day' }) ) // Replace elements in array
filter()
- Function: filter / filter the array with specified conditions, leaving part and removing part
- Return: a new array that meets the criteria
- Syntax:
array.filter((value, index, arr) => {
The callback parameters are the same as those of forEach
return true. If the callback returns true, the current value will be put into the returned new array
return false. If the callback returns false, the current item will not be placed in the returned new array
})
Basic type
// chinese const names = ['Durant', 'Curry', 'Butler', 'Kobe', 'Jordan', 'Chun Ye Ku'] // 1. Find the person whose last name is Ku const result = names.filter((value) => value.startsWith('library')) // index and arr are removed if not used console.log(result) // ['Kuri', 'kuruno'] console.log(names) // ['Durant', 'curry', 'Butler', 'Kobe', 'Jordan', 'Ku chunye'] the array itself remains unchanged
// number const waislines = [20, 40, 19, 70, 105, 60] // Find people with legs less than 60 and sort them in ascending order const result = waislines.filter((value) => value < 60).sort((a, b) => a - b) console.log(result) // [19, 20, 40] console.log(waislines) // Original array [20, 40, 19, 70, 105, 60]
reference type
// Filter object const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Find someone over two meters tall const result = boys.filter((value) => value.height > 200) console.log(result) console.log(boys) // The original array remains unchanged
Handwritten one_ filter()
// Handwritten one_ filter() Array.prototype._filter = function (callback) { const result = [] for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) { result.push(this[i]) } } return result } // Filter object const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Find someone over two meters tall const result = boys._filter((value) => value.height > 200) console.log(result) console.log(boys) // The original array remains unchanged
find()
- Function: search the array according to the specified conditions
- Return: if found, return the first element that meets the condition; Otherwise, undefined is returned
- Syntax: array find((value, index, arr) => {
return true indicates that value meets the criteria. Return value to end the search
return false, then the current value does not meet the criteria. Continue to search
}) - Conclusion: it is the same as filter, but only the first qualified value is returned, not the array
Basic type
const names = ['Durant', 'Curry', 'Butler', 'Kobe', 'Jordan', 'Chun Ye Ku'] // 1. Find the first person whose last name is Ku const result = names.find((value) => value.startsWith('library')) // index and arr are removed if not used const result2 = names.find((value) => value.startsWith('Lee')) console.log(result) // Curry console.log(result2) // undefined console.log(names) // ['Durant', 'curry', 'Butler', 'Kobe', 'Jordan', 'Ku chunye'] the array itself remains unchanged
// number const waislines = [20, 40, 19, 70, 105, 60] // Find the first person with legs less than 60 const result = waislines.find((value) => value < 60) console.log(result) // 20 console.log(waislines) // The original array remains unchanged [20, 40, 19, 70, 105, 60]
reference type
// Filter objects const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Find the first person over two meters tall const result = boys.find((value) => value.height > 200) console.log(result) console.log(boys) // The original array remains unchanged
Handwritten one_ find()
// Handwritten one_ find() Array.prototype._find = function (callback) { for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) { return this[i] } } return undefined } // Filter object const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Find someone over two meters tall const result = boys._find((value) => value.height > 200) console.log(result) console.log(boys) // The original array remains unchanged
findIndex()
- Function: search the array according to the specified conditions
- Return: if found, return the subscript of the first element that meets the condition; Otherwise - 1 is returned
- Syntax: array findIndex((value, index, arr) => {
return true indicates that value meets the criteria. Return the subscript of value in the array to end the search
return false, then the current value does not meet the criteria. Continue to search
})
Basic type
// written words const names = ['Durant', 'Curry', 'Butler', 'Kobe', 'Jordan', 'Chun Ye Ku'] // 1. Find the subscript of the first person whose last name is Ku const result = names.findIndex((value) => value == 'Butler') // index and arr are removed if not used const result2 = names.findIndex((value) => value.startsWith('Lee')) console.log(result) // 2 console.log(result2) // -1 console.log(names) // ['Durant', 'curry', 'Butler', 'Kobe', 'Jordan', 'Ku chunye']
// number const waislines = [20, 40, 19, 70, 105, 60] // Find the array subscript of the first person whose leg length is less than 60 const result = waislines.findIndex((value) => value < 60) console.log(result) // 20 console.log(waislines) // Original array [20, 40, 19, 70, 105, 60]
reference type
// Filter object const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Find the subscript of the first person over two meters tall const result = boys.findIndex((value) => value.height > 200) const result2 = boys.findIndex((value) => value.height > 300) console.log(result) console.log(result2) // -1
Handwritten one_ findIndex()
// Handwritten one_ find() Array.prototype._findIndex = function (callback) { for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) { return i } } return -1 } // Filter object const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Find the subscript of the first person over two meters tall const result = boys._findIndex((value) => value.height > 200) const result2 = boys._findIndex((value) => value.height > 300) console.log(result) console.log(result2) // -1 console.log(boys) // The original array remains unchanged
map()
- Function: mapping, get a new array according to the existing array, and the array elements of the two are one-to-one corresponding
- Return: new array after mapping
- Syntax: array map((item,index,arr) => {
return a new value// Add the new value returned in each callback function to the new array
})
Basic type
// written words const names = ['Durant', 'Curry', 'Butler', 'Kobe', 'Jordan', 'Chun Ye Ku'] // 1. Spell the number after each name const result = names.map((value, index) => value + index) // Returns a new array console.log(result, 'New array') console.log(names, 'Original array') // Add 10 to all the numbers const ages = [15, 18, 17, 20, 50, 45] const result2 = ages.map((value) => value + 10) // Returns a new array console.log(result2, 'New array') console.log(ages, 'Original array')
reference type
// Array of operations const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Add id (subscript + 1) and gender attributes to each object const result = boys.map((value, index) => { return { ...value, id: index + 1, gender: 'female' } }) console.log(result, 'New array') // New array obtained console.log(boys, 'Original array') // The original array remains unchanged
Handwritten one_ map()
Array.prototype._map = function(callback) { const result = [] for (let i = 0; i < this.length; i++) { result.push(callback(this[i], i, this)) } return result } // Array of operations const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Add id (subscript + 1) and gender attributes to each object const result = boys._map((value, index) => { return { ...value, id: index + 1, gender: 'female' } }) console.log(result, 'New array') // New array obtained console.log(boys, 'Original array') // The original array remains unchanged
every()
- Function: detect / judge whether all elements in the array meet the specified conditions
- Return: if all are satisfied, return true; otherwise (as long as one is not satisfied), return false
- Execution process: if a condition is detected that does not meet the conditions, it will be stopped, otherwise the detection will continue
- Syntax: array every((item, index, arr) => {
return Boolean value;
return false: indicates that value does not meet the conditions. Stop execution
return true: indicates that value meets the criteria. Continue to check the next one;
}) - Note: calling every with an empty array will get a true result [] every(()=>{}) //true
Basic type
// written words const names = ['Durant', 'Curry', 'Butler', 'Kobe', 'Jordan', 'Chun Ye Ku'] // 1. Check whether the array is all surnamed Du const result = names.every(value => value.startsWith('Du')) console.log(result, 'Detect whether the array is all surnamed Du') // false to detect whether all the arrays are surnamed Du // 2. Check whether there is no surname Li in the array const result2 = names.every(value => !value.startsWith('Lee')) console.log(result2, 'Check whether there is no surname Li in the array') // true to detect whether the array is not surnamed Li
const ages = [15, 18, 17, 20, 50, 45] // Are all ages above 20 detected in the array const result = ages.every(value => value > 20) console.log(result, 'Check whether the age in the array is more than 20') //false check whether the age in the array is more than 20 // Check whether the age in the array is more than 10 const result2 = ages.every(value => value > 10) console.log(result2, 'Check whether the age in the array is more than 10') //true to check whether the age in the array is more than 10
reference type
// Array of operations const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Judge whether the height in the array is greater than 200cm const result = boys.every(value => value.height > 200) console.log(result) // false // Judge whether the height in the array is greater than 190cm const result2 = boys.every(value => value.height > 190) console.log(result2) // true
Handwritten one_ every()
// Principle of every method Array.prototype._every = function(callback) { for (let i = 0; i < this.length; i++) { // If our instance does not meet the conditions if (!callback(this[i], i, this)) { return false } } // Otherwise, they all meet the conditions return true } // Array of operations const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Judge whether the height in the array is greater than 200cm const result = boys._every(value => value.height > 200) console.log(result) // false // Judge whether the height in the array is greater than 190cm const result2 = boys._every(value => value.height > 190) console.log(result2) // true
some()
- Function: detect and judge whether there are values that meet the specified conditions in the array
- Return: if it exists, it returns true; otherwise (none of the conditions are met) it returns false
- Execution process: if one of the conditions is detected, it will stop. Otherwise, continue the detection
- Syntax:
array.some((value, index, arr) => {
return Boolean
return true: indicates that value meets the criteria and returns true
return false: value does not meet the criteria. Continue to test
})
Basic type
// written words const names = ['Durant', 'Curry', 'Butler', 'Kobe', 'Jordan', 'Chun Ye Ku'] // 1. Check whether there is Du in the array. Where does he first appear const result = names.some((value, index) => { console.log(value.startsWith('Du'), index + 1) // true 1 // If you return true, you won't look down return value.startsWith('Du') }) console.log(result) // true
// number const ages = [15, 18, 17, 20, 50, 45] // Check whether there are those aged over 20 in the array const result = ages.some(value => { console.log(value) return value > 20 }) console.log(result) // true
reference type
// Array of operations const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // //Judge whether the height in the array is greater than 200 cm const result = boys.some(value => { console.log(value.height) // 200 192 205 return value.height > 200 }) console.log(result) // true
Handwritten one_ some()
// Principle of some method Array.prototype._some = function(callback) { for (let i = 0; i < this.length; i++) { // If our instance does not meet the conditions if (callback(this[i], i, this)) { return true } } // Otherwise, they all meet the conditions return false } // Array of operations const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // //Judge whether the height in the array is greater than 200cm const result = boys._some(value => { console.log(value.height) // 200 192 205 return value.height > 200 }) console.log(result) // true
reduce()
reduce(callback,[initiaIValue])
-
Function: summarize and get a final (overall) result according to the existing array, such as summing the array
-
Return: summary (overall) results
-
Two parameters
array.reduce((accumulator, currentValue, currentIndex, array)={
Accumulator: accumulator
currentValue: the element in the current array
currentIndex: the index of the current element in the array
Array: array object itselfinitiaIValue: Optional parameters that affect accumulator Initial value of If not initiaIValue that accumulator From the first element in the array here cuurentValue It will take the second element in the array and start the iteration If given initiaIValue that initiaIValue Back as accumulator Initial value of here currentValue It will take the first element in the array and start the iteration
},[initialValue])
Basic type
No initial value
// Sums the numbers in the array const waistlines = [55, 43, 70, 58] const result = waistlines.reduce((accu, cur, index, arr) => { console.log(accu, cur, index, arr) // Because we don't give an initial value, we start with accu as the initial value // 55 43 1 (4) [55, 43, 70, 58] // 98 70 2 (4) [55, 43, 70, 58] // 168 58 3 (4) [55, 43, 70, 58] // If return, the value of accu is derived from the value returned last time. Otherwise, the second accu is undefined return accu + cur }) console.log(result) // 226
There is an initial value
// Sums the numbers in the array cconst waistlines = [55, 43, 70, 58] const result = waistlines.reduce((accu, cur, index, arr) => { console.log(accu, cur, index, arr) // We give the initial value of the case // 0 55 0 (4) [55, 43, 70, 58] // 55 43 1 (4) [55, 43, 70, 58] // 98 70 2 (4) [55, 43, 70, 58] // 168 58 3 (4) [55, 43, 70, 58] // If return, the value of accu is derived from the last returned value return accu + cur }, 0) console.log(result) // 226
Summary: when can I not give an initial value? Sum and product of pure numbers
reference type
No initial value
const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Without initial value const result = boys.reduce((accu, cur) => { // First time: 200 + 192 // Second time: 392 height + 205 // Third time: NaN + 233 return accu.height + cur.height }) console.log(result) // NaN
There is an initial value
// Reference type for average height const boys = [ { name: 'Durant', height: 200 }, { name: 'Curry', height: 192 }, { name: 'Butler', height: 205 }, { name: 'Kobe', height: 233 } ] // Add the initial value const result = boys.reduce((accu, cur, index) => { // First time: 0 + 200 // Second time: 200 + 192 // Third time: 392 + 205 // Fourth time: 597 + 233 return accu + cur.height }, 0) console.log(result / boys.length) // 207.5
Summary: when must the initial value be given? Objects are summed (summarized) in the array
Address actual needs
- Find the ASCII string from the array ['73', '32', '108', '111', '118', '101', '32', '106', '105', '110']
const ASCII = ['73', '32', '108', '111', '118', '101', '32', '106', '105', '110'] const result = ASCII.reduce((accu, cur) => accu + String.fromCharCode(cur), '') console.log(result) // I love jin
- Total price
// Total price const shopping = [ { name: 'gym shoes', price: 200, num: 2 }, { name: 'Jersey', price: 400, num: 1 }, { name: 'glove', price: 3, num: 6 }, { name: 'Roller-skating', price: 300, num: 10 } ] const result = shopping.reduce((accu, cur) => accu + cur.price * cur.num, 0) console.log(result) // 3818
- Count the number of occurrences of each name: ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']
const names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'] const result = names.reduce((accu, cur) => { accu[cur] = accu[cur] ? accu[cur] + 1 : 1 return accu }, {}) console.log(result)
- According to the data: [Beijing ',' Shanghai ',' Beijing ',' Shenzhen ',' Hangzhou ',' Shanghai ',' Beijing ']
Get the array: ['Beijing', 3], ['Shanghai', 2], ['Shenzhen', 1], ['Hangzhou', 1]]
const citys = ['Beijing','Shanghai','Beijing','Shenzhen','Hangzhou','Shanghai','Beijing'] const result = citys.reduce((accu, cur, index, arr) => { accu[cur] = ++accu[cur] || 1 // if(index === arr.length - 1) {/ / after the last iteration, the overall result is returned // // Object.entries() converts the object to a two-dimensional array // return Object.entries(accu) // }else {/ / this is not the last time. The accu cumulative result is returned // return accu // } // Simplified version return index === arr.length - 1 ? Object.entries(accu) :accu },{}) console.log(result)
Handwritten one_ reduce()
Array.prototype._reduce = function(callback,initiaValue){ // 1. Judge whether the array has passed in the initiaValue const hasinitiaValue = typeof initiaValue !== 'undefined' // 2. If yes, start from 0, but not from 1 let i = hasinitiaValue ? 0 : 1 // 3. Determine the initial value of ACU let accu = hasinitiaValue ? initiaValue : this[0] // Circular array. The starting subscript is determined according to whether there is an initiaValue for(; i < this.length; i++){ // Continuous iteration accu accu = callback(accu, this[i], i, this) } return accu } const citys = ['Beijing','Shanghai','Beijing','Shenzhen','Hangzhou','Shanghai','Beijing'] const result = citys._reduce((accu, cur, index, arr) => { accu[cur] = ++accu[cur] || 1 // if(index === arr.length - 1) {/ / after the last iteration, the overall result is returned // // Object.entries() converts the object to a two-dimensional array // return Object.entries(accu) // }else {/ / this is not the last time. The accu cumulative result is returned // return accu // } // Simplified version return index === arr.length - 1 ? Object.entries(accu) :accu },{}) console.log(result)
flat()
- Functions: flatten arrays, flatten arrays - > eliminate nested arrays - > Convert multi-dimensional arrays to one-dimensional arrays
- Return: array after flattening
- Syntax: array flat(depth = 1)
- Parameter: the depth of flattening. The default value is 1. Only one layer is flattened
- every: no matter how many layers the array is nested, all become one-dimensional, depth can be passed to infinity
Nested three layers
const nums = [[123],[111,[456,[999]]],111,222,333] const result = nums.flat(3) console.log(result) // [123, 111, 456, 999, 111, 222, 333]
Nested multilayer
const nums = [[123],[[[[[[111,[456,[999]]]]]]]],111,222,333] const result = nums.flat(Infinity) console.log(result) // [123, 111, 456, 999, 111, 222, 333]
Handwritten one_ flat()
// Principle of realizing flat method Array.prototype._flat = function(depth = 1){ return flatten(this, depth >= 1 ? depth : 1) function flatten(arr, depth){ // The end identifier of recursion returns a copy of a new array instance if(depth <= 0) return [...arr] return arr.reduce((accu, cur)=>{ if(Array.isArray(cur)){ // cur is an array, which is processed recursively accu.push(...flatten(cur,depth-1)) }else{ // item is not an array. You can add it directly to accu accu.push(cur) } return accu },[]) } } const nums = [[123],[[[[[[111,[456,[999]]]]]]]],111,222,333] const result = nums._flat(Infinity) console.log(result) // [123, 111, 456, 999, 111, 222, 333] const nums1 = [[111],[2222],333,444] const result1 = nums1._flat(1) console.log(result1) // [111, 2222, 333, 444]
Relevant information
- https://es6.ruanyifeng.com/
- https://space.bilibili.com/510273162?spm_id_from=333.788.b_765f7570696e666f.2
The level is limited and can't write about perfection. I hope you can communicate more and make progress with chunye!!!