当前位置:网站首页>JS_ Array_ sort
JS_ Array_ sort
2022-07-03 18:33:00 【Lemon Yakult】
01- review
Scope
overall situation : Everyone can use , Life cycle : Session level , Not recommended ( To use less )
Local : Only internal functions can be used , Life cycle : End of the function , Not recommended
Scope chain : First, see if you have this variable , I didn't find it last time , Until there is no error in the overall situation
recursive
Solve objects with variable layers
object
var obj = {} Literal
var obj2 = new Object() Constructors
obj.name = 'Jack' increase
obj.name = 'Rose' modify
// Only attributes can be deleted , After the dot are all attributes
delete obj.name Delete
console.log(obj.xxx) lookup
console.log(obj['xxx'])
Loop objects
for (var attr in obj) {
attr -> Property name
obj[attr] -> Property value
}
Array
var arr = []
data type
basic :number string boolean undefined null
complex :function object array
There are differences after implementation
// function fn() {
// var a = 12 // Disappear immediately after execution
// }
// fn()
// Closure
// function fn() {
// var a = 12 // a Don't disappear
// function fun() {
// }
// fun()
// }
// fn()
// Variable (delete Only attributes can be deleted )
var a = 100
delete a
console.log(a) // 100
delete Delete attribute question
delete Operator You can only delete your own properties , You cannot delete inherited properties ( To delete an inherited property, you must delete it from the prototype object that defines it , And it will affect all objects inherited from this prototype )
02- practice
Average every five even numbers , Each average value is stored in the new array , Output new array
<script>
// Define an array
var arr = []
// save 30 An even number
for (var i = 2; i <= 60; i += 2) {
arr.push(i)
}
console.log(arr)
// New array
var newArr = []
// Sum up
var sum = 0
// averaging , Put all the average values into a new array
for (var i = 0; i < arr.length; i++) {
// console.log(arr[i])
sum += arr[i]
// Is it the fifth value
if ((i + 1) % 5 === 0) {
// Put the average value into the new array
newArr.push(sum / 5)
// Restart the calculation
sum = 0
}
}
console.log(newArr)
</script>
03- Array
Two dimensional array
var arr = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
....
]
Example : 1-25 Save every five numbers
// Big array
var bigArr = []
// Array
var arr = []
// add to 25 Number
for (var i = 1; i <= 25; i++) {
arr.push(i) // Save number
if (i % 5 === 0) { // Judge whether the array is full 5 There is no value
bigArr.push(arr) // An array with full five values is stored in a large array
arr = [] // Empty , In order to start saving again
}
}
console.log(bigArr)
04- Array writing
// Array
// - [] Literal
// - new Array() Constructors
var arr = [12, 5, 7, 99, 103]
// var arr2 = new Array(100, 200, 300, 400)
// When there is only one value in the constructor, it is the array length
// var arr3 = new Array(10)
// console.log(arr, arr2, arr3)
// Array operation
// - push pop unshift shift
// push
// - At the end of the array
var res = arr.push(20, 31, 66)
// pop
// - Delete the last one in the array
// - Return value : The one deleted
var res = arr.pop()
// unshift
// - Add
var res = arr.unshift(200, 100)
// shift
// - Delete the front of the array
// - Return value : The one deleted
var res = arr.shift()
console.log(arr)
console.log(res)
05- Array exercise
Quote questions ( Address problem , If two complex data types are continuous, one changes and the other changes )
Later, the array changes , The previous array remains unchanged
var arr2 = arr
arr2.push(999)
<script>
var arr = [12, 5, 7, 99, 103, 1]
// Rebuild an array
var arr2 = []
for (var i = 0; i < arr.length; i++) {
arr2.push(arr[i])
}
arr2.push(999)
console.log(arr, arr2)
</script>
06- Encapsulate function operation array
Example : Whether the entered number is in the array
<script>
var arr = [12, 5, 7, 99, 103, 1]
function findArr(arr, n) {
// The array passed by the loop
for (var i = 0; i < arr.length; i++) {
// Every one in the array is associated with the passed parameter n Compare
if (arr[i] === n) {
// Find the direct termination function to run return true
return true
}
}
// There is no entry condition at the end of the cycle , That must be missing return false
return false
}
var b = findArr(arr, 1)
var b2 = findArr(arr, 100)
console.log(b, b2)
</script>
07- practice
Array growth value Each value increases by percent 30, Can't change the original array
<script>
// Array growth value Each value increases by percent 30, Can't change the original array
// - [10, 100, 1000]
var arr = [10, 100, 1000]
function fn(arr, n) {
var newArr = [] // New array
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i] * n) // Multiply each value of the old array by a percentage value Save in the new array
}
// console.log(arr, newArr)
return newArr // Returns a new array
}
var newArr = fn(arr, 1.5) // The array when passing parameters , Magnification Receive a new array
var newArr2 = fn(arr, 2) // The array when passing parameters , Magnification Receive a new array
console.log(newArr, newArr2)
</script>
08- Array operation
Array operation
- push pop shift unshift indexOf slice splice concat reverse join sort
<script>
var arr = [12, 5, 7, 99, 103, 1]
// indexOf
// - lookup
// - Return value : Returns the subscript No return found -1
// var res = arr.indexOf(999)
// console.log(res)
// slice
// - Copy
// - Return value : Returns a new array
// var res = arr.slice()
// var res = arr.slice(3)
// var res = arr.slice(3, 5) // Both parameters are subscripts
// console.log(res, arr)
// splice
// - cut
// - Return value : Returns a new array Change the original array
// var res = arr.splice(1)
// var res = arr.splice(3, 2) // The first parameter is position , The second parameter is the number
// var res = arr.splice(3, 2, 'abc', 100, 200) // The third parameter is added later
// console.log(arr, res)
// concat
// - Linked array
// - Return value : Returns a new array
// var res = arr.concat([100, 200, 300], 'str')
// console.log(arr, res)
// reverse
// - Inversion array
// - Return value : Returns a new array Change the original array
// var res = arr.reverse()
// console.log(arr, res)
// join
// - Turn the string
// - Return value : A string
// var res = arr.join()
// var res = arr.join('')
// var res = arr.join('-')
var res = arr.join('/')
console.log(res)
// sort
// - Sort
// arr.sort() // Can only sort strings a - z
arr.sort(function (a, b) {
// return a - b // From small to large
return b - a // From big to small
})
console.log(arr)
</script>
09- practice
duplicate removal
<script>
// duplicate removal
var arr = ['a', 'b', 'c', 'd', 'b', 'c', 'c', 'd', 'a', 'b', 'c']
arr.sort()
console.log(arr)
for (var i = 0; i < arr.length; i++) {
if (arr[i] === arr[i + 1]) {
// Delete one
arr.splice(i, 1)
i--
}
}
console.log(arr)
</script>
10- Bubble sort
<script>
/*
[5, 7, 12, 99, 1, 103]
[5, 7, 12, 1, 99, 103]
[5, 7, 1, 12, 99, 103]
[5, 1, 7, 12, 99, 103]
[1, 5, 7, 12, 99, 103]
*/
var count = 0
var arr = [12, 5, 7, 99, 103, 1]
for (var j = 0; j < arr.length - 1; j++) {
for (var i = 0; i < arr.length - 1 - j; i++) {
count++
if (arr[i] > arr[i + 1]) {
// Change position
var tmp = arr[i]
arr[i] = arr[i + 1]
arr[i + 1] = tmp
}
}
}
console.log(arr)
console.log(count)
</script>
11- Selection sort
meaning
Choose a maximum value and The current subscript value changes position
Reduce the number of position changes
Choose a maximum value and The current subscript value changes position
Reduce the number of position changes
var i = 0 var maxIndex = 5 [103, 7, 12, 99, 1, 5]
var i = 1 var maxIndex = 3 [103, 99, 12, 7, 1, 5]
var i = 2 var maxIndex = 2 [103, 99, 12, 7, 1, 5]
var i = 3 var maxIndex = 3 [103, 99, 12, 7, 1, 5]
var i = 4 var maxIndex = 5 [103, 99, 12, 7, 5, 1]
<script>
var arr = [12, 5, 7, 99, 103, 1]
var maxIndex = 0
for (var i = 0; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i
}
}
var tmp = arr[0]
arr[0] = arr[maxIndex]
arr[maxIndex] = tmp
var maxIndex = 1
for (var i = 1; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i
}
}
var tmp = arr[1]
arr[1] = arr[maxIndex]
arr[maxIndex] = tmp
var maxIndex = 2
for (var i = 2; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i
}
}
var tmp = arr[2]
arr[2] = arr[maxIndex]
arr[maxIndex] = tmp
var maxIndex = 3
for (var i = 3; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i
}
}
var tmp = arr[3]
arr[3] = arr[maxIndex]
arr[maxIndex] = tmp
var maxIndex = 4
for (var i = 4; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i
}
}
var tmp = arr[4]
arr[4] = arr[maxIndex]
arr[maxIndex] = tmp
console.log(arr)
</script>
11- Selection sort 2
<script>
var arr = [12, 5, 7, 99, 103, 1]
var count = 0
for (var j = 0; j < arr.length; j++) {
var maxIndex = j
for (var i = j; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i
}
}
// Optimize
if (maxIndex !== j) {
count++
var tmp = arr[j]
arr[j] = arr[maxIndex]
arr[maxIndex] = tmp
}
}
console.log(arr)
console.log(count)
</script>
边栏推荐
- 论文阅读 GloDyNE Global Topology Preserving Dynamic Network Embedding
- Bidding procurement scheme management of Oracle project management system
- How does GCN use large convolution instead of small convolution? (the explanation of the paper includes super detailed notes + Chinese English comparison + pictures)
- Line by line explanation of yolox source code of anchor free series network (6) -- mixup data enhancement
- win32:堆破坏的dump文件分析
- [tutorial] build your first application on coreos
- Torch learning notes (3) -- univariate linear regression model (self training)
- How do microservices aggregate API documents? This wave of operation is too good
- Mature port AI ceaspectus leads the world in the application of AI in terminals, CIMC Feitong advanced products go global, smart terminals, intelligent ports, intelligent terminals
- 4. Load balancing and dynamic static separation
猜你喜欢

The vscode code is automatically modified to a compliance code when it is formatted and saved

Three gradient descent methods and code implementation
![AcWing 271. Teacher Yang's photographic arrangement [multidimensional DP]](/img/3d/6d61fefc62063596221f98999a863b.png)
AcWing 271. Teacher Yang's photographic arrangement [multidimensional DP]

Theoretical description of linear equations and summary of methods for solving linear equations by eigen

Xception for deeplab v3+ (including super detailed code comments and original drawing of the paper)

Redis core technology and practice - learning notes (IX): slicing cluster

模块九作业

Naoqi robot summary 27

MySQL duplicate check

What kind of experience is it when the Institute earns 20000 yuan a month?
随机推荐
Install apache+php+mysql+phpmyadmin xampp and its error resolution
Class exercises
SQL injection -day16
2022-2028 global petroleum pipe joint industry research and trend analysis report
199. Right view of binary tree - breadth search
【统信UOS】扫描仪设备管理驱动安装
[tutorial] build your first application on coreos
Redis core technology and practice - learning notes (VIII) sentinel cluster: sentinel hung up
Torch learning notes (6) -- logistic regression model (self training)
Gao Qing, Beijing University of Aeronautics and Astronautics: CIM is a natural quantum computing platform for graph data processing
G1 garbage collector of garbage collector
2022-2028 global lithium battery copper foil industry research and trend analysis report
Kratos微服务框架下实现CQRS架构模式
A. Berland Poker &1000【简单数学思维】
Win32: dump file analysis of heap corruption
189. Rotation array
模块九作业
[combinatorics] generating function (example of generating function | calculating generating function with given general term formula | calculating general term formula with given generating function)
PHP MySQL inserts multiple pieces of data
A. Odd Selection【BruteForce】