1. String inversion, i.e. “I am Tony” becomes “Tony am I”

Str.split (“”).reverse().join(

var s = "I am Tony";
// We need to pass the re to the split function

s.split(/\s+/)
  .reverse()
  .join("");
//"Tony am I"
Copy the code

2. Write a JS script to organize files

Before finishing:

111.232.213 ascqwdwd
111.232.213 qwdqwdqw
122.31.34.1 wdojqwodjqwp
232.34.13.3 adhwdhwqhd
Copy the code

After finishing:

'111.232.213: [' ascqwdwd', 'QWDQWDQW],' 122.31.34.1: [' wdojqwodjqwp], '232.34.13.3: [' adhwdhwqhd]Copy the code

Parse: reads the file, iterates through each line, removes the trailing whitespace in whitespace style, and stores it in JS hashMap

var fs = require("fs");
function processFile(filepath) {
  fs.readFile(filepath, "utf-8", (err, data) => {
    if (err) throw err;
    var arr = data.split("\n");
    var res = {};
    arr.forEach(function(item) {
      var temp = item.trim().split("");
      // If there is no such IP, the IP array is initialized
      if(! res[temp[0]]) {
        res[temp[0]] = [];
      }
      res[temp[0]].push(temp[1]);
    });
    console.log(res);
  });
}
processFile("./test.txt");
Copy the code

3. Javascript string template

All keywords enclosed in curly braces in the string should be replaced with the corresponding key value in the object literal. {href:’www.zyy1217.com’, text:’ yuanyuan xiaowu ‘}}

Render (template, context); render(template, context); Requirements: No control flow components (loops, conditions, etc.) are required, only variable substitution functions can be used. Cascaded variables can also be expanded. Escaped delimiters {and} should not be rendered, and whitespace character codes are allowed between delimiters and variables

function render(template, context) {
  // Matches {} with the preceding escape character
  var reg = / ^ "(. *?) \{(\w+)\}<\/(\1)>$/;
  var reg = / (\ \)? \ {([^ \ {\}]) (\ \)? The \} /;
  template.replace(reg, function(word, slash1, token, slash2) {
    if (slash1 || slash2) {
      return word.replace("\ \"."");
    }
    var current = context;
    var variables = token.replace(/\s/g."").split(".");
    for (var i = 0; i < variables.length; i++) {
      current = current[variables[i]];
      if(! current)return "";
    }
    return current;
  });
}
var template = '<a href="{href}">{text}</a>';
var context = {
  href: "www.zyy1217.com".text: "Yuan Yuan's Nest"
};
render(template, context);
Copy the code

4. Write a sum function to achieve the following effect

// Should equal 15
sum(1.2.3.4.5);
// Should equal 0
sum(5.null.- 5);
// Should equal 10
sum(
  "1.0".false.1.true.1."A".1."B".1."C".1."D".1."E".1."F".1."G".1
);
// Should equal 0.3, not 0.30000000000000004
sum(0.1.0.2);
Copy the code

Simple operations on decimals and small integers can be done as follows, however, overflow may occur:

The default value

function numAdd(num1 /*:String*/, num2 /*:String*/) {
  var baseNum, baseNum1, baseNum2;
  try {
    baseNum1 = num1.split(".") [1].length;
  } catch (e) {
    baseNum1 = 0;
  }
  try {
    baseNum2 = num2.split(".") [1].length;
  } catch (e) {
    baseNum2 = 0;
  }
  baseNum = Math.pow(10.Math.max(baseNum1, baseNum2));
  return (num1 * baseNum + num2 * baseNum) / baseNum;
}
Copy the code

The complete code is as follows:

function sum() {
  var arr = [].slice.call(arguments);
  return arr.reduce(function(prev, next) {
    if (isNaN(next)) return prev;
    basenum1 = prev.toString().split(".") [1]? prev.toString().split(".") [1].length
      : 0;
    basenum2 = next.toString().split(".") [1]? next.toString().split(".") [1].length
      : 0;

    basenum = Math.pow(10.Math.max(basenum1, basenum2));
    return (prev * basenum + next * basenum) / basenum;
  });
}
Copy the code

5. Js checks whether the object is empty

If a={}, then if(! A) isEmptyObject is implemented in a very thoughtful way in jQuery

function isEmptyObject(obj) {
  for (var key in obj) {
    return false;
  }
  return true;
}
Copy the code

6. Add (1)(2)(3), where the number of calls is not limited

Closures are used to store the result of the last addition.

function add(n) {
  var fn = function(x) {
    return add(n + x);
  };
  return fn;
}
Copy the code

In theory, this should solve the problem, but during debugging, we will find that when the function is called, the output is not sum, but add, because we return the function itself after each call; So now the problem is how do I get the function to print sum;

ToString and valueOf are called in JavaScript, so we override toString or valueOf for TMP to return sum.

function add(n) {
  var fn = function(x) {
    return add(n + x);
  };
  fn.valueOf = function() {
    return n;
  };
  return fn;
}
Copy the code

Ok, now we’ve solved the problem by returning the closure recursively; Now, if the number of add parameters is not fixed, such as add(2,3)(5), the above method does not apply; Solutions are as follows:

function add() {
  var sum = 0;
  var arr = [].slice.call(arguments);
  sum = arr.reduce(function(prev, next) {
    return prev + next;
  });
  // for ( var index in arguments){
  // sum = sum+ arguments[index];
  // }
  var fn = function() {
    // for (var val in arguments){
    // sum += arguments[val];
    // }
    var arr = [].slice.call(arguments);
    sum += arr.reduce(function(prev, next) {
      return prev + next;
    });
    return fn;
  };
  fn.toString = function() {
    return sum;
  };
  return fn;
}
Copy the code

Note: Arguments is a parameter object, not an array; So if you want to get parameters there are two ways to do it

Var arr = [].slice. Call (arguments) Uses for in to iterate over argumens objects; Note here that for in traverses the enumerable properties of instances and stereotypes;

for (var val in arguments) {
  sum += arguments[val];
}
Copy the code

7. Find prime numbers up to 1000

function prime(n) {
  var arr = [];
  for (var i = 2; i < n; i++) {
    for (var j = 2; j < Math.sqrt(i); j++) {
      if (i % j === 0) {
        break; }}if (j >= Math.sqrt(i)) { arr.push(i); }}return arr;
}
Copy the code

8. What does the following code output? Why is that?

    console.log(1 + "2" + "2");
    console.log(1 + +"2" + "2");
    console.log(1 + -"1" + "2");
    console.log(+"1" + "1" + "2");
    console.log( "A" - "B" + "2");
    console.log( "A" - "B" + 2);
    // Run it yourself. There are three points to note:

    // When multiple numbers and numeric strings are mixed, it depends on the position of the operand
    console.log(2 + 1 + '3'); / /'33'
    console.log('3' + 2 + 1); / / '321'

    // A numeric string is converted to a numeric string if it is preceded by a sign (+/-) in a numeric string
    console.log(typeof '3'); // string
    console.log(typeof +'3'); //number

    // Again, you can add '' before a number to turn it into a string
    console.log(typeof 3); // number
    console.log(typeof (' '+3)); //string

    // NaN is returned if the result cannot be converted to a number
    console.log('a' * 'sd'); //NaN
    console.log('A' - 'B'); // NaN
Copy the code

9. Add attributes to basic data without error, but the value is undefined

var a = 10;
a.pro = 10;
console.log(a.pro + a);
var s = "hello";
s.pro = "world";
console.log(s.pro + s);
// both a.pro and s.pro are undefined

// Answer :NaN undefinedHello
Copy the code

Adding attributes to primitive data is not an error, but a reference returns undefined,10+undefined returns NaN, and undefined becomes a string when added to string.

10. Look at the following code. What does it output? Explain why;

var a = null;
alert(typeof a); //object
Null is a data type with only one value, which is null;
// represents a null pointer object, so typeof returns "object";
Copy the code

$(document).ready(function(){}); How to implement Jq’s ready method with native JS?

The window.onload() method must wait until all elements of the page, including images, have loaded; $(document).ready() is executed when the DOM structure is drawn, not loaded;

function ready(fn) {
  if (document.addEventListener) {
    // Standard browser
    document.addEventListener(
      "DOMContentLoaded".function() {
        // Cancel events to avoid repeated triggering
        document.removeEventListener(
          "DOMContentLoaded".arguments.callee,
          false
        );
        fn(); // Execute the function
      },
      false
    );
  } else if (document.attachEvent) {
    //IE
    document.attachEvent("onreadystatechange".function() {
      if (document.readyState == "complete") {
        document.detachEvent("onreadystatechange".arguments.callee);
        fn(); // Function execution}}); }}Copy the code

12. Determine if a word is a palindrome?

function checkPalindrom(str) {
  return (
    str ==
    str
      .split("")
      .reverse()
      .join("")); }Copy the code

13. Exchange two integers without using temporary variables

function swap(a, b) {
  b = b - a;
  a = a + b;
  b = a - b;
  return [a, b];
}

module.exports = swap;
Copy the code

14. Find the maximum difference between the following arrays:

Input,5,11,7,8,9 [10]; The output of 6

function maxdiff(arr) {
  var minvalue = arr[0],
    maxprofit = 0;
  for (var i = 0; i < arr.length; i++) {
    minvalue = Math.min(minvalue, arr[i]);
    maxprofit = Math.max(arr[i] - minvalue, maxprofit);
  }
  return maxprofit;
}
Copy the code

15. Implement functionality similar to getElementsByClassName

Implement a function of your own to find all DOM nodes containing a class under a DOM node? Native-provided DOM lookup functions such as getElementsByClassName querySelectorAll are not allowed;

function getElementsByClass(oParent, target) {
  var aEle = oParent.getElementsByTagName("*");
  var aResult = [];
  var i = 0;
  for (i = 0; i < aEle.length; i++) {
    if (aEle[i].className.splite(' ').indexOf(target) > - 1) { aResult.push(aEle[i]); }}return aResult;
}
Copy the code

16. Obtain parameters in the URL

If the parameter name is specified, return the value of the parameter or an empty string. If the parameter name is specified, return the entire parameter object or {}, return an array if more than one parameter of the same name exists

Example:

getUrlParam('http://www.nowcoder.com?key=1&key=2&key=3&test=4#hehe'.'key');

function getUrlParam(sUrl, sKey) {
  var res,
    param = {};
  sUrl.replace(/ [\ &]? (\w+)=(\w+)[&#]/g.function($0, $1, $2) {
    param[$1] = param[$1= = =undefined ? $2 : [].concat(param[$1], $2);
  });
  res = sKey === undefined || "" ? param : param[sKey] || "";
  return res;
}
Copy the code

17. Find the nearest public parent of both nodes

ONode1 and oNode2 are in the same document and will not be the same node
  • The first solution is relatively simple: start from the two nodes, follow the parent pointer to the root node, get two stacks, and then find the first common node of both stacks.
function commonParentNode(oNode1, oNode2) {
  var nodes1 = [],
    nodes2 = [];
  while (oNode1) {
    nodes1.push(oNode1);
    oNode1 = oNode1.parentNode;
  }
  while (oNode2) {
    nodes2.push(oNode2);
    oNode2 = oNode2.parentNode;
  }
  while ((a = nodes1.pop()) === nodes2.pop()) {
    node = a;
  }

  return node;
}
Copy the code
  • The second method uses the Contains method, which iterates through the for loop to find
function commonParentNode(oNode1, oNode2) {
  if(! oNode1 || ! oNode2) {return null;
  }
  for (; oNode1; oNode1 = oNode1.parentNode) {
    if (oNode1.contains(oNode2)) {
      returnoNode1; }}}Copy the code

18. Create objects in the specified space based on the package name

Input description: namespace ({a: {test: 1, b: 2}}, 'A.B.C.D) output description: {a: {test: 1, b: {c: {d: {}}}}}Copy the code

Method one:

function namespace(oNamespace, sPackage) {
  var arr = sPackage.split(".");
  var res = oNamespace; // Preserve the reference to the original object
  for (var i = 0, len = arr.length; i < len; i++) {
    if (arr[i] in oNamespace) {
      // The space name is in the object
      if (typeofoNamespace[arr[i]] ! = ="object") {
        // is the original value
        oNamespace[arr[i]] = {}; // Set this property to empty}}else {
      // The space name is not in the object
      oNamespace[arr[i]] = {};
    }
    oNamespace = oNamespace[arr[i]]; // Point to the next space name property;
  }
  return res;
}
Copy the code

Method two recursion

function namespace(oNamespace, sPackage) {
  if (sPackage.length <= 0) return;
  var pointer = oNamespace;
  if (sPackage[0] in oNamespace) {
    if (typeof oNamespace[sPackage[0]]. = ="object") {
      oNamespace[sPackage[0]] = {}; }}else {
    oNamespace[sPackage[0]] = {};
  }
  oNamespace = oNamespace[sPackage[0]];
  namespace(oNamespace, sPackage.slice(2));
  return pointer;
}
Copy the code

19. Time formatting output

FormatDate (new Date(1409894060000), ‘YYYY-MM-DD HH: MM: SS week w’) example: 2014-09-05 13:14:20 Friday

function formatDate(oDate, sFormation) {
  var obj = {
    yyyy: oDate.getFullYear(),
    yy: ("" + oDate.getFullYear()).slice(2 -),
    MM: ("0" + (oDate.getMonth() + 1)).slice(2 -),
    M: oDate.getMonth() + 1.dd: ("0" + oDate.getDate()).slice(2 -),
    d: oDate.getDate(),
    HH: ("0" + oDate.getHours()).slice(2 -),
    H: oDate.getHours(),
    hh: ("0" + (oDate.getHours() % 12)).slice(2 -),
    h: oDate.getHours() % 12.mm: ("0" + oDate.getMinutes()).slice(2 -),
    m: oDate.getMinutes(),
    ss: ("0" + oDate.getSeconds()).slice(2 -),
    s: oDate.getSeconds(),
    w: ["Day"."一"."二"."Three"."Four"."Five"."Six"][oDate.getDay()]
  };
  return sFormation.replace(/([a-z]+)/gi.function($1) {
    return obj[$1];
  });
}
Copy the code

20. Get the length of the string

If the second argument bUnicode255For1 === true, all characters are 1 in length; otherwise, 2 if the character Unicode encoding is > 255

// Unicode encoding characters greater than 255 can pass
s.charCodeAt(i) > 255;

或者;

s.match(/[\u0256-\uffff]/g);

function strLength(s, bUnicode255For1) {
  // If bUnicode255For1 is false, return the length of s plus the regular matching length of \u0256-\ uFFFF
  return (
    s.length +
    (bUnicode255For1 ? 0 : (s.match(/[\u0256-\uffff]/g) || []).length)
  );
}
Copy the code

###21. Color string conversion

Convert RGB color strings to hexadecimal forms, such as RGB (255, 255, 255) to # FFFFFF per RGB, followed by an unfixed number of Spaces. Hexadecimal expressions use six lower case letters. If input does not fit RGB, return the original input

Rgb2hex (‘ RGB (255, 255, 255)’) output example: # FFFFFF

Utilizes the toString method of the Number object, which returns a string representation of the object in the specified cardinality.

function rgb2hex(sRGB) {
  var res = [];
  var reg = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/g;
  if(! reg.test(sRGB)) {return sRGB;
  } else {
    var reg2 = /(\d+)/g;
    sRGB.replace(reg2, function($0) {
      res.push(("0"+ (+ $0).toString(16)).slice(2 -));
    });
  }
  return "#" + res.join("");
}
Copy the code

22. Convert strings to hump form

CSS often has characters like background-image that are connected by -. When setting the style through javascript, you need to convert the style to backgroundImage hump format. Please complete this conversion function

Capitalizing the first letter of the second non-empty word with a – delimiter -webkit-border-image Converts the result to webkitBorderImage.

CssStyle2DomStyle (‘font-size’)

Replace uses the string. replace method. Note that the replace function takes three arguments: the first is the matched String, the second and third slash is the submatch; The js parameter is passed by value, so you can only get the value through Word, slash1 and slash2. After modifying the matched value, be sure to return it.

function cssStyle2DomStyle(sName) {
  var reg = /(\w)? - + (.). ? /g;
  return sName.replace(reg, function(word, slash1, slash2) {
    if(! slash1)return slash2;
    else {
      return slash2 ? slash1 + slash2.toUpperCase() : slash1 + ""; }}); }Copy the code

24. Capitalize numbers

Write a function fn(Number n) that converts the Number to uppercase;

Input 123 Output 123 First set in caps will measure ’10 million a’ digital to uppercase, and unit of measure eg: two hundred and five billion four hundred and two million and two thousand one hundred and three will be zero (thousand | | hundred 10) replace zero, will replace multiple zero zero, 1 will be zero ($| wan) replace (million | wan);

function fn(n) {
  if (isNaN(n)) {
    return "Illegal data";
  }
  var unit = "Ten thousand, ten thousand, ten thousand, ten thousand.";
  if (n.length > unit.length) {
    return "Data is too long";
  }
  var newStr = "";
  var nlength = n.length;
  unit = unit.substr(unit.length - nlength);
  for (var i = 0; i < nlength; i++) {
    newStr += "One, two, three, four, five, six, eight, nine.".charAt(n[i]) + unit.charAt(i);
  }
  newStr = newStr.substr(0, newStr.length - 1);
  console.log(newStr);
  newStr = newStr
    .replace(/ zero (thousand | | hundred 10)/g."Zero")
    .replace(/ (zero) + / g."Zero")
    .replace(/ zero ($| wan)/g."$1");
  return newStr;
}
Copy the code

25. Deduplicate the js array

1. The easiest way (ES6)

ES6 allows extracting values from arrays and objects and assigning values to variables in a pattern called Destructuring;

Previously, to assign a value to a variable, you could only specify a value directly;

function unique(arr) {
  const seen = new Map(a);return arr.filter(a= >! seen.has(a) && seen.set(a,1));
}
// or
function unique(arr) {
  return Array.from(new Set(arr));
}
Copy the code

2. If you know the sorted array, or do not care about the result order after deduplication; We can do a loop to determine whether the current item is equal to the previous item. If it is not equal to or does not exist in the previous item, we push it to result. (This is quick)

Array.prototype.uniq = function() {
  if (!this.length || this.length === 0) {
    return this;
  }
  this.sort();
  var res = [this[0]].for (var i = 1, len = this.length; i < len; i++) {
    if (this[i] ! = =this[i - 1]) {
      res.push(this[i]); }}return res;
};
Copy the code

3. Or two Pointers L and R are used. L records the position of non-repeating elements, and R traverses the number set starting from the next position of L. If the number in position R is not equal to the number in position L, it indicates that the number is not repeated. You need to put the number in the next position of L and increase L by 1.

Time complexity :O(n)

Space complexity :O(1)

Array.prototype.uniq = function() {
  if (!this.length || this.length === 0) {
    return this;
  }
  this.sort();
  var left = 0,
    right;
  for (right = left + 1, len = this.length; right < len; right++) {
    if (this[left] ! = =this[right]) {
      this[++left] = this[right]; }}return this.slice(0, left);
};
Copy the code

4. If the order is out of order, you can do a loop and use an object to mark whether the item exists or not. If not, push the item to result. A HashTable structure is used to keep track of existing elements, thus avoiding inner loop; However, if the array is very large, the performance will be poor;

if (!Array.prototype.unique) {
  Array.prototype.unique = function() {
    var hash = {},
      result = [],
      item;
    for (var i = 0; i < this.length; i++) {
      item = this[i];
      var key = Object.prototype.toString.call(item) + item;
      if(! hash[key]) { hash[key] =true; result.push(item); }}return result;
  };
}
Copy the code

Note that the hash key value in JS is stored as a character, so the array element used as the hash index needs to add the type, otherwise the number 1 and character 1 cannot be distinguished. Function () = function (); function () = function ();

If we hit an Object, we continue the loop;

Go through the array, create a new array, use indexOf to determine whether it exists in the new array, if not, push to the new array, and finally return the new array

Time complexity O (n^2)

Array.prototype.indexOf =
  Array.prototype.indexOf ||
  function(item) {
    for (var i = 0, j = this.length; i < j; i++) {
      if (this[i] === item) {
        returni; }}return - 1;
  };
function removeDuplicatedItem(ar) {
  var ret = [];
  for (var i = 0, j = ar.length; i < j; i++) {
    if (ret.indexOf(ar[i]) === - 1) { ret.push(ar[i]); }}return ret;
}
Copy the code

When using typeof in JavaScript to judge data types, only basic types can be distinguished, namely “number”,”string”,”undefined”,” Boolean “,”object”.

For arrays, functions, and objects, the relationship is complicated. Using Typeof returns “object” strings.

To distinguish objects, arrays, functions, simply use the typeof is no good, JavaScript, through the Object. The prototype. The toString method, to determine an Object value belong to which kinds of built-in types;

26 array sorts algorithm

The outer loop starts with the second array [2,1,5,4,9,8]; In the first round the second and the first, if the second is smaller than the first, switch places; ,2,5,4,9,8 [1]; In the second round the third and the second, if the second is less than the first, switch places; ,2,5,4,9,8 [1]; In the third round the fourth and the third, if the second is less than the first, switch places; ,2,4,5,9,8 [1]; And so on: the outer cycle can discharge the size;

function insert(arr) {
    var s;
    for (var i = 1; i < arr.length; i++) {
        for (var j = i; j > 0; j--) {
        if (arr[j] < arr[j - 1]) {
            s=arr[j];
            arr[j]=arr[j- 1]
            arr[j- 1]=s
            console.log(arr)   // You can print out each step of the change}}}return arr
}
console.log(insert([3.3.4.2.1.4.4.3.7.8]))
Copy the code

2. Bubble sort

Code demo:

    function bubble(arr) {
        var s
        for (var i =0; i<arr.length; i++) {for (var j = 0; j < arr.length; j++) {
                if (arr[j] > arr[j + 1]) {
                    s = arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=s; }}}return arr
    }
    console.log(bubble([1.2.3.4.5.7.8]));
    
Copy the code

3. Select sort

First find the smallest item in the array, add the new array, and determine the index of the smallest item. According to the index, the current array can only delete the smallest item once, so we add a layer of loop, let it execute multiple times, the number of times is the length of the array

Code demo:

    function select(arr) {
        var result = []
        for (var i = 0, len = arr.length; i < len; i++) {
            var min = Math.min.apply(null, arr)
            result.push(min)
            arr.forEach(function(item, index) {
                if (item == min) {
                    arr.splice(index, 1)}}}return result
    }
    var arr = [3.2.5.4.8.7.1]]
    var res = select(arr)
    console.log(res)
Copy the code

27. Why [” 1 “, “2”, “3”). The map parseInt () returns [1, NaN, NaN]?

The parseInt () function

ParseInt (string, radix) string The string that must be parsed. Radix optional. Represents the radix of the number to be parsed. It is between 2 and 36.

The return value

Returns the parsed number.

The map method

Array1 (callbackfn[, thisArg]) array1 required. An array object. Callbackfn required. A function that takes up to three arguments. The ‘map’ method calls callbackFN once for each element in the array. ThisArg optional. An object for which the ‘this’ keyword can be referenced in the’ callbackfn ‘function. If ‘thisArg’ is omitted, ‘undefined’ will be used as the ‘this’ value.

The return value

Each element is a new array of the value returned by the callback function of the associated original array element

abnormal

If the CallbackFN argument is not a function object, a TypeError exception is raised. note

The map method calls callbackFN once (in ascending index order) for each element in the array. The callback function is not called for missing elements in the array.

In addition to array objects, the map method can be used by any object with a Length attribute that has a numerically indexed attribute name

Return [1,NaN,NaN] cause

Let’s redefine parseInt

var parseInt = function(string, radix) {
    return string + "-" + radix;
};
 
["1"."2"."3"].map(parseInt);
// The output is:
["1-0"."2-1"."3-2"]
 
// Add a parameter

var parseInt = function(string, radix, obj) {
    return string + "-" + radix + "-" + obj;
};
 
["1"."2"."3"].map(parseInt);
// Output result:

["1-0-1, 2, 3"."2-1-1, 2, 3"."3-2-1, 2, 3"];

// Add the following parameters:

var parseInt = function(string, radix, obj, other) {
    return string + "-" + radix + "-" + obj + "-" + other;
};
 
["1"."2"."3"].map(parseInt);

Copy the code

[“1”, “2”, “3”]. Map (parseInt) should correspond to: [parseInt(“1”, 0), parseInt(“2”, 1), parseInt(“3”, 2)] parseInt(“3”, 2) NaN is returned because there is no valid binary number in the string “3”, so NaN

28. The difference between JS forEach and map methods

1. Grammar:

//forEach
array.forEach(callback(currentValue, index, array){
    //do something
}, this)
 
/ / or
array.forEach(callback(currentValue, index, array){
    //do something})&emsp; &emsp;//map:
var new_array = arr.map(callback[, thisArg])&emsp;
 
//$.each()
$(selector).each(function(index,element))
Copy the code

The difference between

1. ForEach () returns undefined, cannot be chained.

2. Map () returns a new array, unchanged.

3. There is no way to terminate or exit the forEach() loop unless an exception is thrown, so you can use a generic for loop to see if an Array satisfies some condition and return a Boolean, or array.every () or array.some ();

The $.each() method specifies a function to run for each matched element, which can return false to stop the loop early.

Loop method performance ranking

The for loop iterates through < for… < forEach < for… In traverse < map traverse

29. Performance comparison and analysis of Array push and unshift methods

Array’s push and unshift methods both add elements to the current Array, except that push adds elements at the end, while unshift adds elements at the beginning. It can be seen from the principle that unshift is inefficient. The reason is that for every element it adds, it moves the existing element down one place. What is the difference in efficiency between the two? So let’s test that out

var arr=[],s = +new Date;
// Push performance tests
for(var i=0; i<50000; i++){ arr.push(i); }console.log(+new Date - s);

s= +new Date;
arr=[];
// Unshift performance test
for(var i=0; i<50000; i++){ arr.unshift(i); }console.log(+new Date - s);
Copy the code

The result was 6,238

Principle: Because if the header element is added, the original position of the array will be scrambled, the array will be reordered, and the performance will be poor. If the tail element is deleted and added, the original subscript position will not be scrambled, the position information will not be scrambled, and the performance is better.

If you must achieve the effect of unshift, you can use push and then reverse the array. Such as:

for (var i = 0; i < 50000; i++) { &emsp; &emsp; arr.push(i); } arr.reverse();// What about reverse performance? Run the following code

var arr = [ ], s = +new Date; 
for (var i = 0; i < 50000; i++) { &emsp; &emsp; arr.push(i); } arr.reverse();console.log(+new Date - s); 

Copy the code

The result is: 8 It can be seen that the reverse performance is very high and basically has no impact

30.JavaScript:(a== 1&&a == 2&&a ==3)

const a = {
  num: 0.valueOf: function() {
    return this.num += 1}};const equality = (a==1 && a==2 && a==3);
console.log(equality); // true
Copy the code

What’s the trick?

There are two concepts in JS:

  • Implicit conversion
  • ValueOf of object

Implicit conversion

Note: in this problem we use == instead of ===, in JS == stands for equal rather than congruent, then there is the problem of implicit transformation of variables. This means that the outcome is more likely than we might expect. There are a lot of articles about implicit conversion of JS. I recommend the following blogs if you want to know about them:

Remember the following two points:

  • Using the equality operator, JS does a cast
  • Our object increments its value by one each time valueOf() is called

31. Implement shallow copy manually

Iterate over the object and place the properties and their values in a new object

    var shallowCopy = function(obj) {
        // Only objects are copied
        if (typeofobj ! = ='object') return;
        // Determine whether to create an array or object based on the type of obj
        var newObj = obj instanceof Array ? [] : {};
        // Iterate over obj and determine if it is obj's property to copy
        for (var key in obj) {
            if(obj.hasOwnProperty(key)) { newObj[key] = obj[key]; }}return newObj;
    }
Copy the code

33. Deep copy implementation

So how do you implement a deep copy? If it is an object, we will recursively call the deep copy function

    var deepCopy = function(obj) {
        if (typeofobj ! = ='object') return;
        var newObj = obj instanceof Array ? [] : {};
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                newObj[key] = typeof obj[key] === 'object'? deepCopy(obj[key]) : obj[key]; }}return newObj;
    }
Copy the code

Implement a javascript new feature

To realize the function of new, we first need to know what new is?

Var a = new a ()

1. Create an empty object obj{}

2. Set a’s this to obj{}

3. Point a’s _proto_ to A’s prototype

4. Execute the constructor of A

5. Return to obj

Code-level implementation:

    function Test (name) {
        this.name = name;
        this.test = '?????? ';
    }
    
    Test.prototype.test2 = function () {
        console.log('Test the prototype on the chain method! ');
    }
    
    function _new () {
        let newObj = {};
        let Constructor = Array.prototype.shift.call(arguments);
        newObj.__proto__ = Constructor.prototype;
        Constructor.apply(newObj,arguments);
        return newObj;
    }

    var t = _new(Test,'yz');
    t.test2();
Copy the code