1. The following questions need to be encapsulated with promise to ensure the order of output

for (var i = 0; i < 5; i++) {
    setTimeOut(function(){
        console.log(new Date(), i);
    }, 1000);
}
console.log(new Date(), i)
Copy the code
function consoless () {
    return new Promise(function(resolve, reject){
        for (var i = 0; i < 5; i++) {
            setTimeout(function() {
                console.log(new Date(), i);
            }, 1000);
        }
        resolve(i);
    })
}
consoless().then(res= > {
    console.log(new Date(), res);
})
Copy the code

2. Output each item

for (var i = 0; i < 5; i++) {
    setTimeOut(function(){
        console.log(new Date(), i);
    }, 1000);
}
console.log(new Date(), i)
Copy the code
for (var i = 0; i < 5; i++) {
    function a(i){
        setTimeOut(function(){
            console.log(new Date(), i);
        }, 1000);
    }
    a(i);
}
console.log(new Date(), i)
Copy the code

3. Binary search

Given an ordered (non-descending) array A, which may contain repeating elements, minimize I such that A[I] is equal to target, and return -1 if it does not exist.

Array =,2,3,5,6,7,7,10 [1]; target = 7, return 5 target = 8, return -1

function search (arr, target) {
    let len = arr.length;
    if (len <= 0) {
        return -1;
    }
    let start = 0;
    let end = len - 1;
    while (start <= end) {
        let mid = Math.floor((start + end)/2);
        if (arr[mid] == target) {
            if (mid - 1> =0 && arr[mid - 1] == target) {
                end = mid - 1;
            } else {
                returnmid; }}else if (arr[mid] > target) {
            end = mid - 1;
        } else {
            start = mid + 1; }}return -1;
}
    console.log(search([1.2.3.5.6.7.7.7.7.7.7.10].7));
Copy the code