1.改变对象key
将 { a_b: ‘111’ } 改成 { aaa: ‘111’ }
var str = {
a_b: '111'
}
var b = JSON.stringify(str)
var e = b.replace(/_b/, 'aa')
var f = JSON.parse(e)
2.随机生成10个10-99的整数并从小到大排序
var arr = []
for (let i = 0; arr.length < 10; i++) {
var x = Math.floor((Math.random() * 90) + 10)
if (arr.indexOf(x) === -1) {
arr.push(x)
}
}
// arr.sort()
// arr.reverse()
console.log(arr.sort(function(a, b) {
return a - b
}), '2')
3.二分法实现开平方sqrt
function sqrt(num) {
function sqrtWrapper(min, max) {
let current = (min + max) / 2;
let nextMin = min;
let nextMax = max;
if (current * current > num) {
nextMax = current;
} else {
nextMin = current;
}
if (nextMax - nextMin < 0.01) {
return current;
} else {
return sqrtWrapper(nextMin, nextMax);
}
}
return sqrtWrapper(0, num);
}
4.js高阶函数
当一个函数作为传参
function add(x, y, f) {
return f(x) + f(y)
}
console.log(add(5, 6, Math.abs));
function pow(x) {
return x * x
}
var arr = [1, 2, 3, 4, 5, 6]
console.log(arr.map(pow))
5.继承
function Person(params) {
this.name = params
}
Person.prototype.age = 10
function Name(params) {
this.a = '44444'
}
Name.prototype = new Person()
var abc = new Name()
console.log(abc, 'abc')
6.async await
async function async1() {
console.log(1);
await async2();
console.log(2)
}
async function async2() {
console.log(3)
}
console.log(4);
async1();
console.log(5)
打印 :4 1 3 5 2