1. Как оценить массив или объект

Справочный ответ:

1.Judging by instanceof
var arr = [1,2,3,1];
console.log(arr instanceof Array) // true

2.via the object's constructor property
var arr = [1,2,3,1];
console.log(arr.constructor === Array) // true

3.Object.prototype.toString.call(arr)
console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]
console.log(Object.prototype.toString.call([]));//[object Array]

4.You can use the new method Array.isArray( ) provided by ES6
Array.isArray([]) //true

2. Глубокая и неглубокая копия объекта, вопрос об Object.assign отдельно.

Справочный ответ:

· Shallow copy: only the basic type of data is copied, and reference type data will also be referenced after copying. We call this copy shallow copy (shallow copy)
  Shallow copy only copies the pointer to an object, not the object itself, and the old and new objects still share the same memory.

· Deep copy: reallocate memory in the heap, and make a new copy of all the properties of the source object, so as to ensure that the reference graph of the object of deep copy does not contain any original object or any object on the object graph, and the copied object is the same as the original The objects are completely isolated and do not affect each other.

The Object.assign method can copy any number of enumerable properties of the source object itself to the target object, and then return the target object. But the Object.assign method performs a shallow copy, which copies the references to the properties of the object, not the object itself.

3. Расскажите о принципе instanceof и ответьте на следующие вопросы.

function A(){}
function B(){}
A.prototype = new B(); 
let a = new A(); 
console.log(a instanceof B) // true of false ?

Справочный ответ:

The answer is true.
instanceof principle:
instanceof is used to check whether an object is an instance of a constructor.
For example: A instance of B
instanceof is used to detect whether the object A is an instance of B, and the detection is based on the prototype chain to search, that is to say, whether the prototype of B is on the __proto__ prototype chain of the object A, if so, return true, otherwise return false

4. Опишите результат выполнения следующего кода

const first = () => (new Promise((resolve, reject) => {
    console.log(3);
    let p = new Promise((resolve, reject) => {
        console.log(7);
        setTimeout(() => {
            console.log(1);
        }, 0);
        setTimeout(() => {
            console.log(2);
            resolve(3);
        }, 0)
        resolve(4);
    });
    resolve(2);
    p.then((arg) => {
        console.log(arg, 5); // 1 bb
    });
    setTimeout(() => {
        console.log(6);
    }, 0);
}))
first().then((arg) => {
    console.log(arg, 7); // 2 aa
    setTimeout(() => {
        console.log(8);
    }, 0);
});
setTimeout(() => {
    console.log(9);
}, 0);
console.log(10);

Справочный ответ:

3
7
10
4 5
2 7
1
2
6
9
8

5. Утечка памяти

Справочный ответ:

Memory leak refers to the heap memory that has been dynamically allocated in the program is not released or cannot be released for some reason, resulting in a waste of system memory, resulting in serious consequences such as slowing down the running speed of the program and even system crashes.
Javascript is a high-level language. It does not need to manually apply for memory like C language, and then release it manually. Javascript automatically allocates memory when declaring variables. Common types such as number are generally placed in stack memory, and objects are placed on the heap. In the memory, declare a variable, allocate some memory, and then perform garbage collection regularly. The task of garbage collection is done by the garbage collector in the JavaScript engine, which monitors all objects and deletes those that are not accessible.
The basic garbage collection algorithm is called "mark-and-sweep" and periodically performs the following "garbage collection" steps:
· The garbage collector takes the roots and **"marks"** (remembers) them.
· It then visits and "marks" all references from them.
· It then visits the marked objects and marks their references. All accessed objects are remembered so that the same object is not accessed twice in the future.
· And so on until there are unvisited references (reachable from the root).
· All objects are deleted except marked objects.

6. Разница между let, const и var

Справочный ответ:

1.Variables defined by var have no concept of blocks, can be accessed across blocks, but cannot be accessed across functions, and have variable promotion.
2.Variables defined by let can only be accessed in the block scope, not across blocks or functions, without variable promotion, and cannot be declared repeatedly.
3.const is used to define constants, must be initialized (that is, must be assigned) when used, can only be accessed in the block scope, and cannot be modified, no variable promotion, and repeated declarations are not allowed.

7. Реализуйте функцию для запроса URL-адреса…

В случае сбоя повторите запрос. Если количество запросов превысит максимальное количество раз, будет выполнен обратный вызов с ошибкой, а каждый раз, когда он будет успешным, будет выполнен успешный обратный вызов.

Справочный ответ:

/**
    @params url: Request interface address;
    @params body: set request body;
    @params succ: callback after successful request
    @params error: Callback after request fails
    @params maxCount: Set the number of requests
*/
function request(url, body, succ, error, maxCount = 5) {
    return fetch(url, body)
        .then(res => succ(res))
        .catch(err => {
            if (maxCount <= 0) return error('Request timed out');
            return request(url, body, succ, error, --maxCount);
        });
}
// call request function
request('https://java.some.com/pc/reqCount', { method: 'GET', headers: {} },
    (res) => {
        console.log(res.data);
    },
    (err) => {
        console.log(err);
    })

8. Пузырьковая сортировка

Справочный ответ:

The core idea of bubble sort is:
1.Compare two adjacent elements, and if the previous one is larger or smaller than the latter (depending on whether the sorting order is small to large or large to small), then exchange the position.
2.After the first round of comparison, the last element is the largest or smallest element.
3.At this time, the last element is already the largest or smallest, so the last element does not need to participate in the comparison when bubbling next time.

Образец кода:

function bSort(arr) {
    var len = arr.length;
    //The outer for loop controls the number of bubbles
    for (var i = 0; i < len - 1; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            // The inner for loop controls the number of comparisons required for each bubble
            // Because the number of pairwise comparisons after each bubbling will be less and less, so -i
            if (arr[j] > arr[j + 1]) {
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}
//give an array
myArr = [20, -1, 27, -7, 35];
//use function
console.log(bSort(myArr)); // [ -7, -1, 20, 27, 35 ]




Дополнительные материалы на PlainEnglish.io.

Подпишитесь на нашу бесплатную еженедельную рассылку новостей. Подпишитесь на нас в Twitter, LinkedIn, YouTube и Discord .

Заинтересованы в масштабировании запуска вашего программного обеспечения? Ознакомьтесь с разделом Схема.