删除
function cut(value) {
return value.slice(0,value.length-1)
}
排序
let arr = [5,2,1,4,9,8] for(let i = 0 ; i < arr.length ; i ++) { for(let j = 0 ; j < arr.length -1 ; j ++) { if(arr[j] > arr[j+1]){ let num = arr[j] arr[j] = arr[j+1] arr[j+1] = num comeout.innerText = arr } }
// 升序 arr.sort(function(a,b){ return a - b }) console.log(arr) // 结果 1,2,4,5,8,9 // 降序 arr.sort(function(a,b){ return b - a }) console.log(arr) // 结果 9,8,5,4,2,1
let arr_choice = [{id:1},{id:3},{id:2},{id:8},{id:6},{id:4}] // 升序 arr_choice.sort(function(a,b){ return b.id - a.id }) console.log(arr_choice) // 结果:[{"id":1},{"id":2},{"id":3},{"id":4},{"id":6},{"id":8}] // 降序 arr_choice.sort(function(a,b){ return b.id - a.id }) console.log(arr_choice) // 结果:[{"id":8},{"id":6},{"id":4},{"id":3},{"id":2},{"id":1}]
let arr_multi = [{id:1,age:10},{id:3,age:5},{id:2,age:6},{id:8,age:8},{id:6,age:5},{id:4,age:5}] // 升序 arr_multi.sort(function(a,b){ // 默认根据年龄排序,年龄相同则按照id排序 if(a.age==b.age){ return a.id - b.id } return a.age - b.age }) console.log(arr_multi) // 结果:[{"id":3,"age":5},{"id":4,"age":5},{"id":6,"age":5},{"id":2,"age":6},{"id":8,"age":8},{"id":1,"age":10}] // 降序 arr_multi.sort(function(a,b){ // 默认根据年龄排序,相同则按照id排序 if(a.age==b.age){ return b.id - a.id } return b.age - a.age }) console.log(arr_multi) // 结果:[{"id":1,"age":10},{"id":8,"age":8},{"id":2,"age":6},{"id":6,"age":5},{"id":4,"age":5},{"id":3,"age":5}]