js and cocos creator study notes

1.What data types does Javascript have? Give examples of the two most common built-in object data types?

常用的数据类型:Number,String,Boolean,Null,Undefined,Object
常见内置对象:Array,Function

2. What is the output of the following code?

let a = [];
a[10] = 10;
console.log(a.length);
console.log(a[0]);
a[200] = undefined;
console.log(a.length);
console.log(a['10']);

    The output is as follows:

console.log(a.length);   //11
console.log(a[0]); //undefined
a[200] = undefined;
console.log(a.length); //201
console.log(a['10']); //10

3. What is the output of the following code?

console.log(null==undefined);
console.log("1"==1);
console.log(0.3 == 0.1+0.2);
let obj1 = {
    
    a:1}; let obj2 = {
    
    a:1};
console.log(obj1==obj2);
let obj3 = obj1; obj3.a=100;
console.log(obj1==obj3);

    The output is as follows:

console.log(null==undefined);   //true
console.log("1"==1);            //true
console.log(0.3 == 0.1+0.2);    //false //这是因为浮点数在计算机中以二进制表示,而一些语言对十进制小数无法精确地表示为有限的二进制小数。0.1 和 0.2 都是十进制小数,但在计算机中以二进制表示时会有一些近似值,但不是完全相等的。 //0.3==0.3 是对的
console.log(obj1==obj2);      //false   引用地址不等
console.log(obj1==obj3);      //true    引用地址相等

4. Under what circumstances will document.addEventListener and document.removeEventListener be cleared and invalid?

Answer:

//错误实例
document.addEventListener('click', boundHandleClick.bind(this));   //错误

// 在某个时刻尝试移除事件监听器
document.removeEventListener('click', boundHandleClick.bind(this));   //错误
/*
*当我们尝试使用 removeEventListener 移除事件监听器时,由于绑定后的函数与原始函数不同,它们无
法匹配,因此无法正确移除监听器。因此,绑定 this 后的函数无法通过绑定后的函数来移除事件监听器。
*/

//正确案例
function handleClick(event) {
    
    
    console.log('点击事件处理程序', this);
}

const boundHandleClick = handleClick.bind({
    
     name: 'Example' });

document.addEventListener('click', boundHandleClick);

// 在某个时刻尝试移除事件监听器
document.removeEventListener('click', boundHandleClick);

5.js, given a numeric type array Array<number>, several ways to return the maximum or minimum value

1种、使用 Math.max() 和 Math.min() 函数:
let arr = [1, 2, 3, 4, 5];  
let max = Math.max(...arr);  
let min = Math.min(...arr);2种、使用 reduce() 函数:
let arr = [1, 2, 3, 4, 5];  
let max = arr.reduce((max, val) => Math.max(max, val), -Infinity);  
let min = arr.reduce((min, val) => Math.min(min, val), Infinity);3种、使用 for 循环:
let arr = [1, 2, 3, 4, 5];  
let max = -Infinity;  
let min = Infinity;  
for(let i = 0; i < arr.length; i++) {
    
      
    if(arr[i] > max) {
    
      
        max = arr[i];  
    }  
    if(arr[i] < min) {
    
      
        min = arr[i];  
    }  
}

6.js string removal of repeated characters.
    (1). Use Set data structure:

const str = "Hello World";
const uniqueStr = [...new Set(str)].join("");
console.log(uniqueStr); // Output: "Helo Wrd"

    This method takes advantage of the properties of the Set data structure, which only stores unique values. After converting the string to a Set object, convert it back to a string to get the result with duplicate characters removed.

    (2), use regular expressions and replace method:

const str = "Hello World";
const uniqueStr = str.replace(/(.)(?=.*\1)/g, "");
console.log(uniqueStr); // Output: "Helo Wrd"

    This method uses regular expressions and positive lookahead to match and remove duplicate characters. Regular expression /(.)(?=.*\1)/gmatches any character and matches if the character is followed by the same character.

  • .: Matches any character.
  • (?=.*\1): Look ahead to ensure that the same character exists after the current position.
  • g: Global match, delete all matching characters.

7.js string removal of certain characters

    (1), use regular expressions and replace method:

const str = "Hello, World!";
const charToRemove = ",";
const removedStr = str.replace(new RegExp(charToRemove, "g"), "");
console.log(removedStr); // Output: "Hello World!"

    This method uses regular expressions to match and replace the characters you want to remove. All matching characters in a string can be removed by passing the characters to be removed as arguments to RegExpthe constructor and specifying the flag for global matching"g"

    (2), use split and join methods:

const str = "Hello, World!";
const charToRemove = ",";
const removedStr = str.split(charToRemove).join("");
console.log(removedStr); // Output: "Hello World!"

    This method makes use of the string's splitand joinmethods. First, use splitthe method to split the string into an array according to the characters to be deleted, and then use jointhe method to merge the array elements into a new string to achieve the purpose of deleting the specified characters.

8. Remove duplicate values ​​from js array
    (1), use Set data structure:

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

This method takes advantage of the properties of the Set data structure, which only stores unique values. After converting the array to a Set object, converting it back to an array will result in removing duplicate values.

    (2), use filter method and indexOf:

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((value, index, self) => {
    
    
  return self.indexOf(value) === index;
});
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

    (3). This method uses filtermethod combined with indexOfmethod to filter out the unique values ​​in the array. In the callback function, determine whether the index of the current element is equal to the index of the first occurrence to determine whether it is a unique value.

//使用 reduce 方法:
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((accumulator, currentValue) => {
    
    
  if (!accumulator.includes(currentValue)) {
    
    
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

    This method uses reducethe method to iterate through the array and determine whether to add to the resulting array based on whether the current value is already contained.

9.js array removes a certain value

    (1), use filter method:

const array = [1, 2, 3, 4, 2, 5];
const valueToRemove = 2;
const filteredArray = array.filter((value) => value !== valueToRemove);
console.log(filteredArray); // Output: [1, 3, 4, 5]

    This method uses filterthe method to filter out the array elements that are not equal to the specific value to be removed, resulting in a new array.

    (2), use splice method:

const array = [1, 2, 3, 4, 2, 5];
const valueToRemove = 2;
for (let i = array.length - 1; i >= 0; i--) {
    
    
  if (array[i] === valueToRemove) {
    
    
    array.splice(i, 1);
  }
}
console.log(array); // Output: [1, 3, 4, 5]

    This method uses splicethe method to directly remove elements from an array that are equal to a specific value. It should be noted that traversing and deleting elements from back to front can avoid the problem of index misalignment.

(3) Use the reduce method:

const array = [1, 2, 3, 4, 2, 5];
const valueToRemove = 2;
const filteredArray = array.reduce((accumulator, currentValue) => {
    
    
  if (currentValue !== valueToRemove) {
    
    
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(filteredArray); // Output: [1, 3, 4, 5]

    This method uses reducethe method to iterate over the array and decide whether to add to the resulting array based on whether the current element is equal to a specific value to be removed.

10.What is the pointing problem of this?
    For example: Bilibili video explains
    that Baidu Yibo has many

11. Understanding of closures and usage scenarios
    such as: Bilibili video analysis

12.js array flattening

function flattenArray(arr) {
    
    
  let result = [];
  arr.forEach(item => {
    
    
    if (Array.isArray(item)) {
    
    
      result = result.concat(flattenArray(item));
    } else {
    
    
      result.push(item);
    }
  });
  return result;
}

// 示例输入
const nestedArray = [1, [2, [3, 4], 5], 6, [7, 8]];

// 调用扁平化函数
const flattenedArray = flattenArray(nestedArray);

// 输出结果
console.log(flattenedArray);  //[1, 2, 3, 4, 5, 6, 7, 8]

new13. How many main things happen during the process of a constructor ?

(可以百度网上有详细说明)
1.创建一个空对象
2.将函数的显示原型赋值给空对象的隐式原型
3.将函数的this指向空对象
4.返回新对象
注意当构造函数返回不是对象时,返回的还是this

14. What are the similarities and differences between js apply, bind and call?

    Apply, bind, and call are methods used to change the execution context of a function. They have some similarities and differences, as well as different implementation principles.

    Same point:

    Change the execution context of a function: apply, bind, and call are all used to change the this pointer inside the function, that is, specify the context object when the function is executed.
difference:

    Parameter passing method: Both apply and call can pass parameters to functions, but in different ways. apply accepts an array or array-like object containing parameters, while call accepts parameters enumerated one by one. bind can bind some parameters and return a new function. The new function can be called later and pass the remaining parameters.

    Return value: The apply and call methods will execute the function immediately when called and return the result of the function. The bind method returns a new function and does not execute the original function immediately.


cocos creator questions
1. What is the principle of screen adaptation?
    (1). Design resolution. For art design exams, a resolution size is needed to provide a reference for development and design and to adapt to different mobile phone resolutions.
    (2).Adaptation strategy: Adaptation height/Adaptation width.
For example, in the horizontal screen of the game, if we adapt the height, we need to make a ratio conversion between the design height in the design draft and the viewport height, so that in the game screen , the display effect is the display effect converted in proportion.
For different models of mobile phones, the height and width of the mobile phones are different, which may not necessarily match the height-to-width ratio of the design draft. How to achieve layout and position effects?
    ① Stop points: In the game, you can use the Widget component script to move or center the top, bottom, left, and right points; ② Adjust the
    size and width of the border area;
    ③ Content scaling or layout through Layout;

2. What is the life cycle and use of cocos creator?
    (1) Life cycle overview:

    onLoad: Called immediately after the node is loaded, used to initialize some settings of the node and components.
    start: Called after onLoad is executed, used to perform operations that need to wait until all nodes and components are initialized.
    update: Will be called every frame to update game logic and status.
    lateUpdate: called after update, used to perform some operations that need to be performed after update.
    onDestroy: Called before the node is destroyed to perform some cleanup work.
How to use life cycle:

    In Cocos Creator, you can use these lifecycle functions by defining them in script components.
    Write the corresponding functions in the script component, such as onLoad(), start(), update(), etc., and implement the corresponding logic inside the function.
    These functions will be automatically called at the corresponding timing. You can perform initialization settings, resource loading, game logic updates, etc. inside the functions.
    If you need to mount a script component on a node and use its life cycle function, you can select the node through the editor interface and add the corresponding component.

Life cycle considerations:

    The execution order of lifecycle functions is fixed, and you can rely on these orders to correctly manage game objects and state.
Avoid performing time-consuming operations in life cycle functions to avoid affecting game performance.
Perform resource release and cleanup work in the onDestroy life cycle function to avoid memory leaks and resource waste.

3. What are the differences and functions of onLoad and start in the life cycle of cocos creator?
    (1), onLoad life cycle function:

    Function: Called immediately after the node is loaded, used to initialize some settings of the node and components. It is an entry point into the initialization phase.

    When to call: The onLoad function will be called when the node and its components are instantiated and added to the scene. Before the onLoad function is executed, the properties of nodes and components have been assigned values, but at this time there is no guarantee that the onLoad functions of other related nodes and components have been executed.

    Usage scenarios: In onLoad, you can perform operations such as initialization settings, obtaining references, and registering event listeners. Asynchronous operations such as resource loading and network requests can also be performed in this function, but you need to pay attention to the execution time and order of asynchronous operations.
    (2), start life cycle function:

    Function: After onLoad is executed, the start function will be called. It is the entry point after nodes and components have completed initialization.

    Calling time: When the node and its components are initialized, the start function will be called. Before the start function is executed, the onLoad functions of all nodes and components have been executed.

    Usage scenarios: In start, you can perform some operations that need to wait for all nodes and components to be initialized before they can be executed, such as animation playback, timer startup, game logic initialization, etc.

4. What are the functions and uses of cocos creator's life cycle ondisable and ondestroy?
They are used to manage the disabling and destruction process of game objects.

    (1), onDisable life cycle function:

    Function: Called when the node is disabled, used to perform some operations that need to be performed when the node is disabled.
Calling time: The onDisable function will be called when the node is disabled (such as removing the node from the scene or disabling the node's parent node).
    Usage scenarios: In onDisable, you can pause some node-related logic, stop timers, cancel event listeners and other operations.
    Note: The onDisable function will not be called when the node is first created, it will only be triggered when the node was previously activated and disabled.
    (2), onDestroy life cycle function:

    Function: Called before the node is destroyed, used to perform some cleanup work and resource release operations.
    Calling time: When the node is destroyed (such as removing the node from the scene or directly calling the node's destroy method), the onDestroy function will be called.
    Usage scenarios: In onDestroy, you can release node and component resources, cancel event listeners, clean up timers and other operations.
    Note: The onDestroy function is called when the node is about to be destroyed. At this time, the properties and methods of the node and components are still available, but other related nodes and components may have been destroyed.
It should be noted that disabling a node does not trigger the onDestroy function immediately. If you need to perform some operations before the node is destroyed, you can perform related processing in onDisable, or call the node's destroy method externally to actively trigger the onDestroy function.

5. How does cocos creator hot update work?
Cocos Creator's hot update feature allows code and resources to be updated while the game is running without having to re-publish the entire game. The following is the basic principle of Cocos Creator hot update:

    Server-side resource storage:

    During the hot update process, a server is required to store the updated resource files of the game. HTTP or other network protocols are usually used to download and update resources.
    Version management:

    In the game, a version number needs to be defined to identify the current game version. You can use a configuration file or data returned by the server API to get the latest game version number.
    Resource update check:

    When the game starts, it sends a request to the server to check if a new version is available for update. Usually the version number of the local game is compared with the latest version number on the server.
    Download updated resources:

    If a new version is available for update, the game will obtain the list of resources that need to be updated based on the resource list file provided by the server (usually a JSON file).
    The game will download resource files to the local storage device one by one according to the resource list. You can use the downloader provided by Cocos Creator or customize the download logic.
    Update resource files:

    After the download is completed, the game will replace the old local resource files with the new resource files. This way the game will load the latest files when using resources.
    Code update checks and replacements:

    For updates to JavaScript code, you can use the eval function or dynamically create

6. What is the difference between xml and json?
    XML (Extensible Markup Language) and JSON (JavaScript Object Notation) are two commonly used data exchange formats. They have the following differences:

Grammatical structures:

    XML uses a hierarchical structure of tags and attributes to represent data, such as content.
JSON uses the structure of key-value pairs to represent data, such as { "key": "value" }.
Data type support:

    XML does not directly support data types, and all data is represented in the form of strings. It needs to be parsed and converted according to the needs of the application.
    JSON supports a variety of data types, including strings, numbers, Boolean values, arrays, objects, etc.
readability:

    XML is self-describing, and tags and attributes can be named more readable and understandable.
    JSON's syntax is more concise and may be easier to read and write for complex data structures.
File size:

    XML files are generally larger than JSON files because XML uses more tags and attributes.
    JSON files are relatively small because they use a concise key-value structure.
Parsing and serializing:

    Parsing and serializing XML requires the use of additional libraries or custom parsers.
    JSON parsing and serialization are natively supported by JavaScript and can be operated directly using JSON.parse() and JSON.stringify().
Data interaction:

    XML is more commonly used in fields such as SOAP, RSS, and configuration files in transmission and interaction.
    JSON is more commonly used in web applications, especially for interaction and data transfer with the JavaScript language.
Choosing to use XML or JSON depends on specific needs and scenarios. XML is more suitable for data with complex structure and self-descriptive requirements, while JSON is more suitable for lightweight data exchange and interaction with JavaScript. In addition, factors such as compatibility with other systems, tools, and languages ​​as well as the efficiency of data transfer should also be considered.

7. Does the object pool consume CPU or GPU?
    Object Pool is a design pattern used to manage reusable object instances to improve performance and resource utilization. Object pools are typically implemented by maintaining a set of pre-created objects in memory and retrieving objects from the pool when needed, rather than frequently creating and destroying objects.

    The object pool itself does not directly involve CPU (Central Processing Unit) or GPU (Graphics Processing Unit) consumption. It is a software design pattern that focuses on the reuse and management of resources.

    However, in certain contexts, the use of object pools may have a certain impact on CPU or GPU consumption. For example, in game development, the use of object pools can reduce the frequent creation and destruction of objects, thereby reducing CPU overhead. This is because the creation and destruction of objects involves operations such as memory allocation and release, and the object pool can avoid these overheads and improve performance.

    On the other hand, the use of object pools can also have a certain impact on the GPU, especially in scenarios involving graphics rendering. The object pool can manage reusable rendering resources (such as textures, models, etc.), thereby reducing the cost of resource loading and release and improving GPU efficiency.

    In general, object pooling itself is a software design pattern that does not directly involve CPU or GPU consumption. However, by optimizing the reuse and management of resources, object pools can have a positive impact on CPU and GPU consumption in specific contexts, improving performance and resource utilization.

Guess you like

Origin blog.csdn.net/mingketao/article/details/132260110