当前位置:网站首页>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>
边栏推荐
- [Godot] add menu button
- Gao Qing, Beijing University of Aeronautics and Astronautics: CIM is a natural quantum computing platform for graph data processing
- 虚拟机和开发板互Ping问题
- 统计图像中各像素值的数量
- win32:堆破壞的dump文件分析
- 12、 Service management
- Computer graduation design PHP makeup sales Beauty shopping mall
- AcWing 271. Teacher Yang's photographic arrangement [multidimensional DP]
- 2022-2028 global marking ink industry research and trend analysis report
- English语法_形容词/副词3级 - 倍数表达
猜你喜欢
[enumeration] annoying frogs always step on my rice fields: (who is the most hateful? (POJ hundred practice 2812)
2022-2028 global sepsis treatment drug industry research and trend analysis report
2022-2028 global physiotherapy clinic industry research and trend analysis report
Computer graduation design PHP campus address book telephone number inquiry system
CTO and programmer were both sentenced for losing control of the crawler
Golang string (string) and byte array ([]byte) are converted to each other
Multifunctional web file manager filestash
2022-2028 global petroleum pipe joint industry research and trend analysis report
Torch learning notes (3) -- univariate linear regression model (self training)
G1 garbage collector of garbage collector
随机推荐
[combinatorics] exponential generating function (properties of exponential generating function | exponential generating function solving multiple set arrangement)
虚拟机和开发板互Ping问题
2022-2028 global petroleum pipe joint industry research and trend analysis report
12、 Service management
论文阅读 GloDyNE Global Topology Preserving Dynamic Network Embedding
Nodejs (01) - introductory tutorial
2022-2028 global aircraft head up display (HUD) industry research and trend analysis report
Setinterval CPU intensive- Is setInterval CPU intensive?
Bidding procurement scheme management of Oracle project management system
This diversion
Naoqi robot summary 27
Valentine's day, send you a little red flower~
[linux]centos 7 reports an error when installing MySQL "no package MySQL server available" no package ZABBIX server MySQL available
Administrative division code acquisition
[enumeration] annoying frogs always step on my rice fields: (who is the most hateful? (POJ hundred practice 2812)
Computer graduation design PHP campus address book telephone number inquiry system
PHP determines which constellation it belongs to today
[combinatorics] exponential generating function (example of exponential generating function solving multiple set arrangement)
Solve the problem of inaccurate network traffic monitored by ZABBIX with SNMP
Win32: analyse du fichier dump pour la défaillance du tas