Good programmer Web front end questions Javascript summary, I believe that now participate in the Web front-end interview must be many, in order to help you successfully through the interview, today prepared the front end questions series, through the Web knowledge arrangement and experience summary, I hope to help more to participate in the front-end interview small partners.
1. How do I check if a variable is a String in JavaScript? Write the function implementation
Methods 1.
function isString(obj){
return typeof(obj) === "string"? true: false;
// returntypeof obj === "string"? true: false;
}Copy the code
Method 2,
function isString(obj){
return obj.constructor === String? true: false;
}Copy the code
Methods 3,
function isString(obj){
return Object.prototype.toString.call(obj) === "[object String]"?true:false;
}Copy the code
Such as:
var isstring = isString('xiaoming');
console.log(isstring); // trueCopy the code
2, please remove string whitespace with js?
Method 1: Use the replace regular matching method
Remove all Spaces: STR = str.replace(/\s*/g,””);
Remove the two Spaces: STR = STR. Replace (/ ^ | \ \ s * * $s/g, “”);
Remove left Spaces: STR = str.replace(/^\s*/, “”);
Remove the right space: STR = str.replace(/(\s*$)/g, “”);
STR is the string to remove whitespace, as shown in the following example:
var str = ” 23 23 “;
var str2 = str.replace(/\s*/g,””);
console.log(str2); / / 2323
Method 2: Use str.trim()
Str.trim () limitations: Can’t remove intermediate Spaces, as shown in the following example:
var str = ” xiao ming “;
var str2 = str.trim();
console.log(str2); //xiao ming
Similarly, str.trimleft () and str.trimright () are used to remove left and right Spaces from the string, respectively.
$.trim(STR); $.trim(STR)
$.trim(STR) limitations: Cannot remove intermediate Spaces, as shown in the following example:
var str = " xiao ming ";
var str2 = $.trim(str)
console.log(str2); // xiao mingCopy the code
Examples are as follows:
function showWindowHref(){
var sHref = window.location.href;
var args = sHref.split('? ');
if(args[0] == sHref){
return "";
}
var arr = args[1].split('&');
var obj = {};
for(var i = 0; i< arr.length; i++){ var arg = arr[i].split('=');
obj[arg[0]] = arg[1];
}
return obj;
}
var href = showWindowHref(); // obj
console.log(href['name']); // xiaomingCopy the code
Js string manipulation functions
Concat () – Combines two or more characters of text to return a new string.
IndexOf () – Returns the index at the first occurrence of a substring in a string. If there is no match, -1 is returned.
CharAt () – Returns a character at the specified position.
LastIndexOf () – Returns the index that appears at the end of a substring in the string, or -1 if there is no match.
Match () – Checks whether a string matches a regular expression.
The substr() function — returns a string of length from the startPos position of string
Substring () – Returns a substring of the string. The incoming arguments are the start and end positions.
Slice () – Extracts a portion of the string and returns a new string.
Replace () – Finds the string that matches a regular expression, and replaces the matching string with the new string.
Search () – Performs a regular expression match lookup. Returns the matched index in the string if the search succeeds. Otherwise -1 is returned.
Split () – Makes a string an array of strings by splitting the string into substrings.
Length – Returns the length of the string, which is the number of characters it contains.
ToLowerCase () – converts the entire string toLowerCase.
ToUpperCase () – converts the entire string toUpperCase.
4. How to add, remove, move, copy, create, and find nodes?
1) Create a new node
CreateDocumentFragment () // Create a DOM fragment
CreateElement () // Create a specific element
CreateTextNode () // Create a text node
2) Add, remove, replace, insert
The appendChild () / / added
The removeChild () / / remove
The replaceChild () / / replace
The insertBefore () / / insert
3) to find
GetElementsByTagName () // Pass the tag name
GetElementsByName () // Passes the value of the element’s Name attribute
GetElementById () // Unique by element Id
Name three typical applications that use this
1), used in HTML element event attributes, such as:
<input type= "button" onclick = "showInfo (this);" Value = "Click" />Copy the code
2) constructor
function Animal(name, color) {
this.name = name;
this.color = color;
}Copy the code
3) Input Click to obtain the value
<input type="button" id="text" value="Click on it" />
<script type="text/javascript">
var btn = document.getElementById("text");
btn.onclick = function() { alert(this.value); } </script>Copy the code
4) Apply ()/call(
var numbers = [5, 458 , 120 , -215 ]; var maxInNumbers = Math.max.apply(this, numbers); console.log(maxInNumbers); // 458 var maxInNumbers = Math.max.call(this,5, 458 , 120 , -215); console.log(maxInNumbers); / / 458Copy the code
6. Compare typeof with Instanceof?
Similarities: Typeof and instanceof are commonly used in JavaScript to determine whether a variable is empty or of what type.
The return value is a string specifying the data typeof a variable.
Details:
Typeof usually returns only the following results:
Number, Boolean, string, the function, object, undefined.
2), typeof to obtain whether a variable exists, such as if(typeof a! =”undefined”){alert(“ok”)}, do not use if(a) because if a does not exist (undeclared) it will fail.
3) For Array,Null and other special objects, use Typeof to return object. This is the limitation of Typeof.
Definition and usage of Instanceof: Instanceof is used to determine whether a variable belongs to an Instanceof an object.
Example demonstration:
a instanceof b? alert("true"):alert("false"); // A is an instance of B? Var a = new Array(); alert(a instanceof Array); //true
alert(a instanceof Object) // trueCopy the code
Alert (an instanceof Object) also returns true; This is because Array is a subclass of Object.
function test() {}; var a = newtest(a); alert(a instanceoftest) / /trueCopy the code
Details:
(1) as follows, the result is’ N ‘, where the object of the instanceof test refers to the object of the JS syntax, not the DOM model object.
if (window instanceof Object){ alert('Y')} else { alert('N'); } / /'N'Copy the code
7. How to understand closures?
1) Definition and usage: A closure is generated when a function returns a value from another function that calls other variables inside its parent function and is executed outside the parent function.
2) Presentation: Enable external functions to call variables defined inside the function.
3) Examples are as follows:
(1) According to the rules of scope chain, variables in the bottom scope that are not declared will be searched one level up and returned. If they are not found, they will continue to be searched until the variables in window are returned. This is obviously the count in flag2 inside of the function.
var count=10; // The global scope is flag1function add(){ var count=0; // The function's global scope is flag2return function(){ count+=1; // Inner scope of function alert(count); } } var s = add() s(); // output 1 s(); 2 / / outputCopy the code
4) Scope of variables
To understand closures, you must first understand Javascript’s special variable scope.
Scope classification of variables: global variables and local variables.
Features:
1. Global variables outside the function can be read inside the function, but local variables inside the function cannot be read outside the function.
2. Use the var command when declaring variables inside a function. If you don’t, you’re actually declaring a global variable!
5) Considerations for using closures
(1) Abuse of closure, will cause memory leakage: because the closure will make the variables in the function are saved in memory, memory consumption is very large, so can not abuse closure, otherwise it will cause performance problems of the web page, may lead to memory leakage in IE. The solution is to remove all unused local variables before exiting the function.
(2) will change the value of the variable inside the parent function. So, if you use a parent function as an object, a closure as its Public Method, and internal variables as its private values, be careful not to arbitrarily change the values of the parent function’s internal variables.
Talk about garbage collection mechanism and memory management
Recovery mechanism mode
1, Definition and usage :Garbage Collection (GC), the execution environment is responsible for managing the memory used during code execution.
2. How it works: The garbage collector periodically (periodically) finds variables that are no longer in use and frees their memory. However, this process is not real-time because it is expensive, so the garbage collector executes it periodically at regular intervals.
3. Examples are as follows:
function fn1() {
var obj = {name: 'hanzichi', age: 10};
}
function fn2() {
var obj = {name:'hanzichi', age: 10};
return obj;
}
var a = fn1();
var b = fn2();Copy the code
Obj defined in Fn1 is a local variable, and when the call ends, out of the fN1 environment, then the block memory will be automatically released by the GARBAGE collector in the JS engine; When fn2 is called, the returned object is referred to by the global variable B, so the block is not freed.
Garbage collection strategy: tag cleanup (more common) and reference counting.
Mark clearance:
Definition and usage: mark a variable as “in” when it enters the environment, and “out” when it leaves the environment. At some point, the garbage collector filters out variables in the environment, as well as variables referenced by environment variables, leaving variables that are considered ready for collection.
So far, JS implementations of Internet Explorer, Firefox, Opera, Chrome, and Safari have all used a marked sweep garbage collection strategy or similar strategies, with different garbage collection intervals.
Reference count:
Definition and usage: Reference counting keeps track of how many times each value is referenced.
Basic principle: is the number of references to a variable, is referenced once plus 1, when the reference count is 0, is considered to be ready to recycle the object.
Memory management
1. When is garbage collection triggered?
The garbage collector runs periodically, and if the amount of memory allocated is very high, the collection can be difficult, so it becomes a worthwhile consideration to determine the garbage collection interval.
Garbage collection in IE6 is based on memory allocation, which is triggered when the number of variables, objects, and strings in the environment reaches a certain number. The garbage collector is always working, which severely affects browser performance.
In IE7, the garbage collector dynamically adjusts the amount of memory allocated to the percentage of memory consumed by the program to start the collection.
2. A reasonable GC scheme :(1) iterate through all accessible objects; (2) Reclaim unreachable objects.
3. GC defects :(1) stop responding to other operations.
4. GC optimization strategy :(1) Generation GC; (2) Incremental GC.
9. How to solve the memory leak during development?
1. Definition and Usage:
A memory leak is when a block of allocated memory is neither used nor reclaimed until the browser process terminates. Languages such as C# and Java use automatic garbage collection to manage memory with almost no memory leaks. We know that automatic garbage collection is also used to manage memory in browsers, but the browser garbage collection method is buggy and can cause memory leaks.
2. Several cases of memory leakage:
(1) When the element in the page is removed or replaced, if the event bound to the element is still not removed, it will not be properly processed in IE. At this time, it is necessary to manually remove the event, otherwise there will be memory leakage.
Examples are as follows:
<div id="myDiv">
<input type="button" value="Click me" id="myBtn">
</div>
<script type="text/javascript">
var btn = document.getElementById("myBtn");
btn.onclick = function(){
document.getElementById("myDiv").innerHTML = "Processing...";
}
</script>Copy the code
Solutions are as follows:
<div id="myDiv">
<input type="button" value="Click me" id="myBtn">
</div>
<script type="text/javascript">
var btn = document.getElementById("myBtn");
btn.onclick = function(){
btn.onclick = null;
document.getElementById("myDiv").innerHTML = "Processing...";
}
</script>Copy the code
(2) Because the function is defined inside the function, and the internal function — the reference to the event callback is exposed, forming a closure. Closures can hold local variables in a function without freeing them.
Examples are as follows:
function bindEvent(){
var obj=document.createElement("XXX");
obj.onclick=function(){
//Even if it's a empty function } }Copy the code
Solutions are as follows:
function bindEvent(){
var obj=document.createElement("XXX");
obj.onclick=function(){
//Even if it's a empty function } obj=null; }Copy the code