Given a poem
守法朝朝忧闷,强梁夜夜欢歌;
损人利己骑马骡,正值公平挨饿;
修桥补路瞎眼,杀人放火儿多;
我到西天问我佛,佛说:我也没辙!
Foreword
Reading "learning JavaScript data structures and algorithms" - Chapter 3 array, this section will continue to share relevant knowledge of an array of small partner for you: ES6 array of new features.
A, ES6 array of new features
ES5 and ES6 array of new methods
method | description |
---|---|
@@iterator | Returns an iterator object comprising an array of key-value pairs, can be obtained by calling the synchronization of the key array element |
copyWithin | Copy the array element number of the array to the same position of the specified start |
entries | @@ iterator Returns an array of all the key-value pairs |
includes | Returns If there is an element of the array true, false otherwise |
find | Find elements from an array callback function according to the given conditions, if find returns that element |
findIndex | Find elements from an array callback function according to the given conditions, if it finds the element index in the array is returned |
fill | Fill the array with static values |
from | According to the existing array to create a new array |
keys | @@ iterator returns an array containing all indexes |
of | Create a new array based on the parameters passed |
value | Returns an array of all worth @@ iterator |
In addition to the above new method of increasing the iteration loop for ... of the array and the object obtained from the array instance iterator
for...of
Iterative array
let roles = ['宋江', '吴用', '卢俊义']
for (let v of roles) {
console.log(v)
}
@@iterator
You need to be accessed by Symbol.iterator
let iterator = roles[Symbol.iterator]()
// .next()读取一次,依次迭代即可; 当迭代结束时,iterator.next().value返回undefined
console.log(iterator.next().value)
// 迭代
for (let v of iterator) {
console.log(v)
}
entries
Return @@ iterator contains key-value pairs
let rolesEntries = roles.entries()
console.log(rolesEntries.next().value) // [ 0, '宋江' ]
for (v of rolesEntries) {
console.log(v)
}
keys
@@ iterator returns an array containing the index
let rolesKeys = roles.keys()
console.log(rolesKeys)
for (v of rolesKeys) {
console.log(v)
}
values
It returns an array containing values @@ iterator
let rolesValues = roles.values()
console.log(rolesValues)
for (v of rolesValues) {
console.log(v)
}
Array.from
According to the existing array to create a new array
let newRoles = Array.from(roles)
console.log(newRoles) // ['宋江', '吴用', '卢俊义']
Array.of
Create a new array of the passed parameter
let roles = Array.of('宋江', '李顺', '阮小七')
console.log(roles) // [ '宋江', '李顺', '阮小七' ]
Array.fill
Use static values filling
let numbers = new Array(6)
numbers = Array.fill(1)
console.log(numbers) // [ 1, 1, 1, 1, 1, 1 ]
copyWithin
A series of elements in the array are copied to the same array specified starting position
let numbers = [1, 2, 3, 4, 5, 6]
// 将索引3到索引5位置之间的数据,复制到索引1位置
numbers.copyWithin(1, 3, 5)
console.log(numbers) // [ 1, 4, 5, 4, 5, 6 ]
Sorting an array
rerverse
Reverse array elements
let numbers = [1, 2, 3]
numbers.reverse()
console.log(numbers) // [ 3, 2, 1 ]
sort
An array in alphabetical order, the function support incoming sorting algorithm specified as a parameter
let arr = ['a', 'b', 'd', 'c', 'f', 'e']
arr.sort()
console.log(arr) // [ 'a', 'b', 'c', 'd', 'e', 'f' ]
So the question is! The following code console.log () What is the output?
let numbers = [1, 2, 3, 10, 11, 12, 13]
numbers.sort()
console.log(numbers) // ??? 思考10秒钟.....
Answer: [1, 10, 11, 12, 13, 2, 3] .gif manually doubt
Analytical: sort () method of the array elements during sorting, so the default string elements compared with each other.
How then to solve practical problems, to get the results we want it?
let numbers = [1, 2, 3, 10, 11, 12, 13]
numbers.sort((a, b) => a - b)
console.log(numbers) // [ 1, 2, 3, 10, 11, 12, 13 ]
Thinking upgrade: String comparison - sensitive comparison
let users = ['Ana', 'ana', 'John', 'john']
users.sort()
console.log(users) // ???
The answer: [ 'Ana', 'John', 'ana', 'john'] manual doubt .gif
Analysis: When the JS comparing strings to be compared according to the ASCII value of the character corresponding to. A, J, a, j is the ASCII equivalent: 65,74,97,106
Solve the problem
let users = ['Ana', 'ana', 'John', 'john']
users.sort((a, b) => {
if (a.toLocaleLowerCase() > b.toLocaleLowerCase()) {
return 1
}
if (a.toLocaleLowerCase() < b.toLocaleLowerCase()) {
return -1
}
return 0
})
console.log(users) // [ 'Ana', 'ana', 'John', 'john' ]
If you want to achieve lowercase letters sorted first, a method may be used localCompare
users.sort ((a, b) = > a.localeCompare (b))
The actual business scenarios: a series of data Sort: such as age, level, etc.
let users = [
{
name: '王二狗',
age: 20
},
{
name: '张三炮',
age: 30
},
{
name: '李四',
age: 15
}
]
users.sort((a, b) => a.age > b.age)
console.log(users) // [ { name: '李四', age: 15 }, { name: '王二狗', age: 20 }, { name: '张三炮', age: 30 } ]
Array Search
ES5 provides indexOf () and lastIndexOf () method finds the elements for us, but the two methods only query string data, such as a query array object to an element of the incompetent.
Business scenario: cart Add product operation
When we add a product to the shopping cart, to consider whether the item already exists in the shopping cart.
Already exists, the purchase quantity + 1; otherwise, the new cart operation.
Original approach: iterate cart array myCart, and id id to be added to determine the existing commodities Cart tmpGoods were compared and, if yes, to get the current element index, perform the operation
Embrace new changes ES6 it! - findIndex
// 已有购物车商品信息
let myCart = [
{
id: 1001,
name: 'xxx-范冰冰版',
num: 1
},
{
id: 1002,
name: 'xxx-志玲姐姐版',
num: 2
},
{
id: 1003,
name: 'xxx-小岳岳版',
num: 1
}
]
// 待加入购物车的商品
let tmpGoods = {
id: 1003,
name: 'xxx-小岳岳版',
num: 1
}
// 检测该商品是否已经存在于购物车
let index = myCart.findIndex(item => item.id === tmpGoods.id)
console.log(index)
if (index !== -1) {
myCart[index].num += tmpGoods.num
} else {
myCart.push(tmpGoods)
}
console.log(myCart)
findIndex support incoming filter as a function of the specified conditions, returns the first matching element index position, or -1 if there is no
find support incoming function specified as a condition, it returns the first matching element value
ES7 - includes
The method includes matching elements based on whether there is an array of query conditions, if there is return true; false otherwise
let roles = ['诸葛亮', '荆轲', '虞姬', '亚瑟']
console.log(roles.includes('荆轲')) // true
console.log(roles.includes('哪吒')) // false
A string output array
toString () and join () method
All elements of the array output as a string
let numbers = [1, 2, 3, 4]
console.log(numbers.toString()) // 1,2,3,4
join
Elements of an array using the specified character spliced default,
let numbers = [1, 2, 3, 4]
console.log(numbers.join('-')) // 1-2-3-4
postscript
And that Hu brother today to share content, like a small partner to remember 收藏
, and 转发
click the bottom right button to 在看
recommend it to more junior partner Yo, welcome to a lot of message exchanges ...
Hu brother something to say, a skill, a feeling of Hu brother! Jingdong open platform chief front-end siege lion. Talk with you big front-end, front-end share system architecture framework implementation principle, the latest and most efficient technology practice!
Press scan code concerned, more handsome and more beautiful Yo! No public attention Hu brother something to say, can continue in-depth exchanges with Hu brother Yo!