[TOC]

Back to directory ↑

Operators and expressions

  • Arithmetic operations

A positive number that’s not 0 divided by 0 is Infinity and a negative number that’s not 0 divided by 0 is minus Infinity. 0/0 is NaN

console.log(1 + 2 * 3);  / / 7
console.log(1 + 3 % 2); / / 2
console.log("" + 3 % 2); / / '1'
console.log(+"" + 3 % 2); / / 1
console.log(+{} + ""); //'NaN'
console.log(100 % 4 / 0); //NaN
console.log(null / null); //NaN
var a;
console.log(a + {} + 123);// 'undefined[object Object]123'
console.log(1 + "" + 2 + 3);/ / '123'
console.log({} * null);  //NaN
console.log(+"" + 100); / / 100

console.log('\n\t\f' / 2 +100); / / 100
console.log('b' + 'a' + (+'a') + 'a');//'baNana'
Copy the code
  • 0 + null + true+ [] + undefined + null + 10 + [] + 'js learning '

What to print on the console

1 undefinednull10js learning

  • What does the following code output
var a = 'abc' + 123 + 456; //'abc123456'
var b = '456' - '123'; / / 333
var c = 100 + true + 21.2 + null + undefined + "Tencent"+ + []null + 9 + false; //'NaNTencentnull9false'
console.log(a,b,c)
Copy the code
  • What does the following code pop up
var str = 'abc123';
var num = parseInt(str);
if(num == NaN) {
  alert(NaN);
} else if(num == 123) {
  alert(123);
} else if(typeof num == 'number') {
  alert('number');
} else {
  alert('str');
}
Copy the code

'number'

  • Autoincrement and autodecrement operation (difficult)

The operational details of the priority

  1. Look from left to right
  2. If you encounter operands, pull the data straight out
  3. If two adjacent operators are encountered and the priority of the left operator is greater than or equal to that of the right operator, the left operator is directly evaluated

Refer to the infix expression code

  • Evaluate the output of the following code
      var x = 1;
      var y = x + x++ * ++x;
      console.log(y)  / / 4
Copy the code
      var x = 1;
      var y = x++ + ++x + x++ * ++x + ++x;
      console.log(y) / / 25
Copy the code
      var x = 1;
      var y = x + ++x * ++x + x;
      console.log(y) / / 10
Copy the code
      var x = 1;
      var y = x + x++ * (x = x + x++ * ++x) + x;
      console.log(y) / / 21
Copy the code
  • Comparison operator

  • What does the following equality operator print in the browser

  '0'= =true         // false
  [1] = = [1]          // false
  [1] = =1            // true
  null= =false       // false
  null= =undefined   // true
  NaN= = =NaN         // false
  +0= = = -0           // true
  Object.is([], [])   // false
  Object.is(-0, +0)   / / false. See SameValue
  Object.is(NaN.NaN) / / true. See SameValue

  var arr = [NaN.0, +0]
  arr.indexOf(-0)     / / 1. See = = =
  arr.indexOf(NaN)    / / 1. See = = =
  arr.includes(-0)    / / true. See SameValueZero
  arr.includes(NaN)   / / true. See SameValueZero
Copy the code
  • What does the following code output
console.log('1'> =10); //false
console.log('2' > true); //true
console.log(NaN > 0);  //false
console.log(3 > {}); //false
console.log(null > -1); //true
console.log(undefined > -1);//false
Copy the code
  • Logical operator

  • Print the code below to output the result

var x = 1;
console.log(x++ >= 1 && x++ >=2 && x++ >= 4 && x++ >= 4); //false
console.log(x);/ / 4
Copy the code
  • Print the code below to output the result
console.log(0 || null || undefined || 1 || null || NaN); / / 1
Copy the code
  • Determine if it’s a leap year

4 years a leap, a hundred years not leap; A leap in 400

console.log(year % 4= = =0 && year % 100! = =0 || year % 400= = =0);
Copy the code
  • Interest calculator: Deposit principal, number of months, and annual interest rate separately to calculate interest. If you deposit more than 100,000 yuan, the annual interest rate increases by 20%(e.g., 4%, 4% * 1.2).
var money = 200000,
  month = 12,
  rate = 4;
money > 100000 && (rate = rate * 1.2);
var lixi = money * rate / 100 / 12 * month;
console.log(lixi);
Copy the code
  • Ternary operator

  • What does the following code output

var x = 1;
x = x++ >= 1 ? x++ * x++ : ++x * ++x;
console.log(x);/ / 6
Copy the code

Back to directory ↑

Basic data types

  • What are the ones that can print “1”
A alert(1)
B console.log(parseInt(1.3))
C console.log(1)
D console.log(isNaN(1))
E console.log(parseInt("1"))
Copy the code

A

  • And then the result is undefined
A console.log(alert(1))
B typeof undefined
C console.log(parseInt(undefined))
D isNaN(undefined)
Copy the code

No value is returned. By default, undefined is returned

  • The following result can be true
A isNaN(null)
B isNaN(parseInt(null))
C new Number(null)
D parseFloat(null)
Copy the code

B

  • Output the results of the following program
parseInt("") //NaN
Number("")   / / 0
isNaN("")    //false
parseInt(null)//NaN
Number(null) / / 0
isNaN(null)   //false
parseInt("12px")/ / 12
Number("12px")//NaN
isNaN("12px") //true
Copy the code
  • The following program output is
if(isNaN(NaN) = ="") {
  console.log("Front end")}else {
  console.log("Training")}Copy the code

training

Back to directory ↑

Reference types

  • What does the following code print on the console
 var obj = {
 num:100.m:obj.num * 10
  } 
Copy the code

Console print value:

VM1829:3 Uncaught TypeError: Cannot read property 'num' of undefined
at <anonymous>:3:11Because the value is evaluated first, in the case of associating a value with an attribute (and this is also true of ordinary variable assignments) in the case of evaluation, obj is not yet associated with the object, but insteadundefined
Copy the code
  • What does the following program output
let n = [10.20];
len m = n;
let x = m;
m[0] = 100;
x = [30.40];
x[0] = 200;
m = x;
m[1] = 300;
n[2] = 400;
console.log(n, m, x);
Copy the code

The output result of

n: 100 20 400 m: 200 300 x: 200 300

  • What does the following program output
let x = [1.2.3];
let y = x;
let z = [4.5.6];
y[0] = 10;
y = z;
z[1] = 20;
x[2] = z = 30;
console.log(x, y, z);
Copy the code

x [10 2 30]

y [4 20 6]

z 30

  • What does the following program output
let a = {
  n:1
};
let b = a;
a.x = a = {
  n:2
};
console.log(a.x);
console.log(b);
Copy the code

undefined {n:1,{n:2}}

  • What does the following code output
      var user1 = {
        name:"u1".address: {
          country:"China".city:"Harbin"}};var user2 = {
        name:"u2".address:user1.address
      };
      user2.name = "user2";
      user2.address.city = "Chengdu";
      console.log(user1.name,user2.name);         //u1,user2
      console.log(user1.address.city,user2.address.city) // Chengdu chengdu
Copy the code
      var obj1 = {
        a: "123".b: "456".sub: {
          s1: "abc".s2: "bcd"}};var obj2 = obj1;
      obj2.sub = {
        s1: "s".s2: "ddd"
      };
      console.log(obj1.sub.s1, obj2.sub.s1); //s, s
Copy the code
  • What does the following code output
var a = 0;
var b = a;
b++;
alert(a); / / 0
var o = {};
o.a = 0;
var b = o;
b.a = 10;
alert(o.a); / / 10
Copy the code

Back to directory ↑

Flow control statement

If judgment

  • What does the following code output
if(! x) { x =1;
}
if (x++ >= 1) {
  var x;
  x++;
} else if (++x >= 2) {
  x++;
} else {
  x--;
}
console.log(x);/ / 3
Copy the code
  • The system prompts the user to enter a three-digit number. If the number is not three digits, the system prompts the user to enter an incorrect number. If the number is three digits, the system determines whether the number is divisible by 13
var result = +prompt("Please enter a three-digit number");
if(isNaN(result) || result < 100 || result >999) {
  console.log('Input error');
} else {
  if(result % 13= = =0) {
    console.log('Divisible by 13.')}else {
    console.log('Not divisible by 13.'); }}Copy the code
  • Ask the user to input A score (0-100), determine which range the score belongs to, and output the result (A:90-100 B:70-89 C:60-69 D:40-59 E:0-39). If the user input A number other than 0-100, it determines that the user input is incorrect
var score = +prompt("Please enter your score");
if (isNaN(score) || score > 100 || score < 0) {
  alert('Input error');
} else if(score >= 90){
  alert('A');
} else if(score >= 70) {
  alert('B');
} else if(score >= 60) {
  alert('C');
} else if(score >= 40) {
  alert('D');
} else {
  alert('E');
}
Copy the code
  • According to calculations recommended by the World Health Organization,

Male standard weight calculation method is (height cm-80) * 70% female standard weight calculation method is (height Cm-70) * 60% standard weight plus or minus 10% is normal weight, less than 10% of the standard weight is too thin, more than 10% of the standard weight is too fat program, let the user input gender, height, There are three kinds of health conditions: 1) your weight is normal, please keep it; 2) your body is too thin, please strengthen nutrition; 3) Your body is too fat, please strengthen exercise

var gender = prompt('Please enter your gender (male, female)');
var height = +prompt('Please enter your height (cm)');
var weight = +prompt('Please enter your weight (kg)');
if (isNaN(height) || isNaN(weight) || gender ! = ='male'&& gender ! = ='woman') {
  alert('Input error');
} else {
  var standWeight;
  gender === 'male' && (standWeight = (height - 80) * 0.7);
  gender === 'woman' && (standWeight = (height - 70) * 0.6);
  if (weight > standWeight * 1.1) {
    alert('Your body is too fat, please take more exercise');
  } else if (weight >= standWeight * 0.9) {
    alert('Your weight is normal. Keep it up.');
  } else {
    alert('Your body is too thin, please strengthen nutrition'); }} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the judgment can also write -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --if(weight < standWeight * 0.9) {
  alert('Your body is too thin, please strengthen nutrition')}else if(weight <= standWeight * 1.1) {
  alert('Your weight is normal. Keep it up.')}else {
  alert('Your body is too fat, please take more exercise')} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the judgment can also write -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --if(weight < standWeight * 0.9) {
  alert('Your body is too thin, please strengthen nutrition');
} else if(weight > standWeight * 1.1) {
  alert('Your body is too fat, please take more exercise');
} else {
  alert('Your weight is normal. Keep it up.');
}
Copy the code
  • If the user’s wealth management amount is less than 500,000 yuan, the annual benefit will be calculated at 4%

If the user’s financial planning amount is more than 500,000 yuan (including 500,000 yuan), the annual benefit will be calculated at 4.5%. If the user’s financial planning amount is more than 2 million yuan, in addition to the financial planning benefit, an additional 10% of the benefit amount will be given to the user

var money = +prompt("Please enter the amount");
var year = +prompt("Please enter the number of years");
if(isNaN(money) || isNaN(year) || money <= 0 || year <= 0) {
  alert('Illegal input');
} else {
  var income;
  if(money < 500000) {
    income = money * 0.04 * year;
  } else if(money < 2000000) {
    income = money * 0.045 * year;
  } else {
    income = money * 0.045 * year * 1.1;
  }
}
alert(income);
Copy the code
  • Write a guessing game between the user and the computer. The user inputs scissors, rock, paper, and the computer’s punches are compared to judge the winner
var fist = prompt('Please enter your punch: Rock, Paper, Scissors');
if(fist ! = ='stone'&& fist ! = ='scissors'&& fist ! = ='cloth') {
  alert('Input illegal');
} else {
  var ran = Math.random();
  var computfist;
  if (ran < 0.3333) {
    computfist = 'stone'
  } else if (ran < 0.6666) {
    computfist = 'scissors';
  } else {
    computfist = 'cloth';
  }
  if(fist === 'stone' && computfist === 'scissors' || fist === 'scissors' && computfist === 'cloth' || 
    fist === 'cloth' && computfist === 'stone') {
    alert('You punch${fist}Computer punch is${computfist}You have won)}else if(fist === computfist) {
    alert('You punch${fist}Computer punch is${computfist}, draw `);
  } else {
    alert('You punch${fist}Computer punch is${computfist}You lost); }}Copy the code

Back to directory ↑

The for loop

  • What does the following for loop output
for (var i = 10; i > 4; i -= 2) {
  if (i < 7) {
    i++;
  } else{ i--; }}console.log(i) / / 4
Copy the code
  • What does the following loop output
for (var i = 0; i < 10; i++) {
  if (i >= 2) {
    i += 2;
    continue;
  }
  if (i >= 6) {
    i--;
    break;
  }
  i++;
  console.log(i); / / 1
}
console.log(i); / / 11
Copy the code
  • What does the following loop output
var i = 0;
while(i < 10) {
  if(i === 3) {
    i++;
    continue;
  }
  console.log(i);
  i++;
}
console.log("Circular introduction", i);
Copy the code

0 1 2 4 5 6 7 8 9 End of loop 10

Back to directory ↑

Application of cycles (emphasis)

Accumulative problem (define variable sum) Search problem (define variable isFind)

  • Take the sum of all the numbers from 1 to 100
  • Multiply numbers 1 to 10
  • All the odd numbers from 1 to 100
  • Is there a number between 135 and 145 that divisible into 26
  • Print all numbers between 135 and 185 that are divisible into 26
  • Prints the first divisible 26 number between 135 and 185, if not present, the output does not exist
Common code routines for finding problems//
var isFind = false;
for (var i = 135; i <= 185; i++) {
  if(i % 26= = =0) {
    console.log(i);
    isFind = true;
    break; }}if(! isFind) {console.log('Nonexistence');
}
Copy the code
  • Determine whether a number is prime
var isFind = false;
for (var i = 2; i < num; i++) {
  if (num % i === 0) {
    isFind = true;
    break; }}if(isFind || num <= 1) {
  console.log('Not prime');
} else {
  console.log('prime');
}
Copy the code
  • Prints all prime numbers between 1 and 100
for (var i = 1; i <= 100; i++) {
  var isFind = false;
  for (var j = 2; j < i; j++) {
    if(i % j === 0) {
      isFind = true;
      break; }}if(! isFind && i >1) {
    console.log(i); }}Copy the code
  • Output 100 * on the console

  • Let the user enter the number of * signs, and then print the corresponding number of *

  • Output an * with three rows and five columns

  • Output a 5-line isosceles triangle with an asterisk, as shown below

    *
   ***
  *****
 *******
*********
Copy the code
var r = 5
for (var i = 1; i <= r; i++) {
  var str = ' ';
  // Concatenate Spaces, the number of Spaces is r-i
  for (var j = 0; j < r - i; j++) {
    str += ' ';
  }
  // The number is 2 * i-1
  for (var j = 0; j < 2 * i - 1; j++) {
    str += The '*';
  }
  console.log(str);
}
Copy the code
  • Find the sum of all prime numbers between 1 and 100
var sum = 0;
for (var i = 1; i <= 100; i++) {
  var isFind = false;
  for (var j = 2; j < i; j++) {
    if (i % j === 0) {
      isFind = true;
      break; }}if(! isFind && i >1) { sum += i; }}console.log(sum);

Copy the code
  • Output 99 times table
for (var i = 1; i <= 9; i++) {
  var str = ' '
  for (var j = 1; j <= i; j++) {
    str += `${j} × ${i} = ${i * j}\t`;
  }
  console.log(str);
}
Copy the code
  • Let’s say the investment has an annual interest rate of 5%. Try to figure out how many years it takes to grow from $1,000 to $5,000
 /* * How many years does it take to grow from 1000 to 5000 if the annual interest rate of investment is 5% * * 1000 1000*1.05 * 1050 1050*1.05 */

// Define a variable that represents the current amount of money
var money = 1000;

// Define a counter
var count = 0;

// Define a while loop to calculate the amount of money per year
while (money < 5000) {
    money *= 1.05;

    // Make count increment
    count++;
}

console.log(money);
console.log("All we need." + count + "Year");

Copy the code
  • Upgrade the guessing game, record the system and the player’s points, the winner adds 1 point, draw and lose no points

You can refer to the following effects:

Game start = = = = = = = = = = = = = = = = = = = = = = = = = = = = = round 1 = = = = = = = = = = = = = = = = = = = = = system: 0, players: 0 you punch: punch scissors systems: cloth you win! = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 2 rounds of = = = = = = = = = = = = = = = = = = = = = = = = = = system: 0, players: 1 minute you punch: stone system punches: cloth, you lose! = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = game = = = = = = = = = = = = = = = = = = = = = = = = = = system: 1, players: 1Copy the code
var count = 1,
  pcScore = 0,
  playerScore = 0;
console.log('Game on');
while (true) {
  console.log(` = = = = = = = = = = = = = the first${count}Round = = = = = = = = = = = = = = = = = = = `);
  console.log(` system:${pcScore}Points, players:${playerScore}Points `);
  var fist = prompt("Your punch (rock, paper, scissors)");
  // Exit the game without punching
  if (fist === null) {
    break;
  }
  if (fist == 'stone' || fist == 'scissors' || fist == 'cloth') {
    // Get the system punch
    var ran = Math.random();
    if (ran < 0.3333) {
      var pcFist = 'stone';
    } else if (ran < 0.6666) {
      var pcFist = 'scissors';
    } else {
      var pcFist = 'cloth';
    }
    console.log('Your punch:${fist}`);
    console.log('System punch:${pcFist}`);
    // Compare wins and losses
    if (fist == 'stone' && pcFist == 'scissors' || fist == 'scissors' && pcFist == 'cloth' ||
      fist == 'cloth' && pcFist == 'stone') {
      console.log('You won');
      playerScore++;
    } else if (fist == pcFist) {
      console.log('draw');
    } else {
      console.log('You lost');
      pcScore++;
    }
    // Increase the number of rounds
    count++;
  } else {
    console.log('No punch, please try again.'); }}console.log('= = = = = = = = = = = = = = = = = = = = = = = game = = = = = = = = = = = = = = = = = = = = = = =');
console.log(` system:${pcScore}Points, players:${playerScore}Points `);

Copy the code

Back to directory ↑

An array of

  • What does the following code output
var arr = [3.6.23.4];
arr[0] = 10;
arr["0"] = 5;
console.log(arr[0], arr["0"]);/ / 5 5
Copy the code
  • What does the following code output
var obj = {
    '2':3.'3':4.'length':2.'splice':Array.prototype.splice,
    'push':Array.prototype.push
}
obj.push(1);
obj.push(2);
obj.push(3);
console.log(obj);
Copy the code

The answer is shown below

  • Reverses the order of the elements of an array of strings in four ways.

Tip: the i-th and length-i-1 are swapped. (In many ways)

/ / method
// Use a double pointer
var arr = [1.2.3];
var myreverse = function(arr) {
  var i = 0,
    j = arr.length - 1,
    newArr = arr.slice();
  while (i < j) {
    var temp = newArr[j];
    newArr[j] = newArr[i];
    newArr[i] = temp;
    i++;
    j--;
  }
  returnnewArr; } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --/ / method 2Use the native methods of arrays//
arr = arr.reverse();
-------------------------------
/ / method 3
// Iterate from the last item to the first item, storing each value in the new array
function myreverse(arr) {
  var newArr = [];
  for (var i = arr.length - 1; i >= 0; i--) {
    newArr[newArr.length] = arr[i];
  }
  return newArr;
}

4 / / method
// Swap the ith element with length-i-1
function myreverse(arr) {
  var newArr = arr.slice();
  for (var i = 0; i < newArr.length / 2; i++) {
    var temp = newArr[i];
    newArr[i] = newArr[newArr.length - i - 1];
    newArr[newArr.length - i - 1] = temp;
  }
  return newArr;
}

Copy the code
  • Prompts the user to enter the length of the array, along with the value of each item in the array, and then prints the array
var len = +prompt("Please enter the length of the array");
if (isNaN(len) || len < 0) {
  console.log('Wrong input, please re-enter');
} else {
  var arr = [];
  for (var i = 0; i < len; i++) {
    var value = prompt('Please enter the number in the array${i + 1}The value of the item `);
    arr[i] = value;
  }
  console.log(arr);
}
Copy the code
  • Initialize an array of numbers and find the sum of the items in the array
  • Initialize an array and print all the odd numbers in that array
  • Initialize an array and print all the primes in that array
  • Let the user enter the length of the Fibonacci sequence and print the Fibonacci sequence in the console
var len = +prompt("Please enter the length of the Fibonacci sequence.");
if (isNaN(len) || len <= 0) {
  console.log('Input error');
} else {
  var arr = [];
  for (var i = 0; i < len; i++) {
    if (i === 0 || i === 1) {
      arr[i] = 1;
    } else {
      arr[i] = arr[i - 1] + arr[i - 2]; }}}console.log(arr);
Copy the code
  • Define an array of users. Each item in the array is a user object. The user object contains the account and password

Array, and prompts the user to enter the account and password to determine whether the login is successful

      var users = [
        { loginId: 'abc'.loginPwd: '123' },
        { loginId: 'abcd'.loginPwd: '1234' },
        { loginId: 'abbb'.loginPwd: '1235' },
        { loginId: 'aaaa'.loginPwd: '1236'},]var loginId = prompt('Please enter your account number');
      var loginPwd = prompt('Please enter your password');
      var isFind = false;
      for (var i = 0; i < users.length; i++) {
        if (loginId === users[i].loginId && loginPwd === users[i].loginPwd) {
          isFind = true;
          break; }}if (isFind) {
        console.log('Login successful');
      } else {
        console.log('Login failed');
      }
Copy the code
  • Initialize a 5 by 5 two-dimensional array, where each entry is a number, and calculate the sum of the diagonals
var arr = [
  [11.12.13.14.15],
  [21.22.23.24.25],
  [31.32.33.34.35],
  [41.42.43.44.45],
  [51.52.53.54.55]]var sum = 0;
for (var i = 0; i < arr.length; i++) {
  for (var j = 0; j < arr[i].length; j++) {
    if (i === j || j === (arr[i].length - i - 1)) { sum += arr[i][j]; }}}console.log(sum);
Copy the code
  • Initialize an array of numbers (numbers are arbitrary), sort the array in ascending order, and print the result
var arr = [9.8.7.22.18.4.3.2.1];
  
bubbleSort(arr);
console.log(arr);

function bubbleSort(arr) {
  var swap = false;
  for (var i = 0; i < arr.length - 1; i++) {
    for (var j = 1; j < arr.length - i; j++) {
      if (arr[j] < arr[j - 1]) {
        var temp = arr[j];
        arr[j] = arr[j - 1];
        arr[j - 1] = temp;
        swap = true; }}if(! swap) {break; }}}Copy the code
  • There’s an array of numbers, and find the number that comes up most often
      var arr = [ 3.4.5.4.4.2.5.9.2.4.5.2.6.9];
      var obj = {};
      for (var i = 0; i < arr.length; i++) {
        if(obj[arr[i]]) {
          obj[arr[i]]++;
        } else {
          obj[arr[i]] = 1; }}var record = {
        prop:undefined.frequency:undefined
      };
      for(var prop in obj) {
        if(obj[prop] > record["frequency") | |! record["prop"]) {
          record.prop = +prop;
          record.frequency = obj[prop]
        }
      }
      console.log(record);
Copy the code
  • Define a myArray() object that simulates an Array() object and declares methods push(),pop(), and toString()
      function myArray() {

        this.length = arguments.length;
        for (var i = 0; i < arguments.length; i++) {
          this[i] = arguments[i];
        }

        this.push = function() {
          for (var i = 0; i < arguments.length; i++) {
            this[this.length] = arguments[i];
            this.length++;
          }
          return this.length;
        }

        this.pop = function() {
          var value = this[this.length - 1];
          delete this[this.length - 1];
          this.length--;
          return value;
        }
        this.toString = function() {
          var result = ' ';
          for (var i = 0; i < this.length; i++) {
            result += this[i];
            if(i < this.length - 1) {
              result += The '*'; }}returnresult; }}var arr = new myArray(11.22.33.44.55);
      arr.push(12.120.220);
      arr.pop();
      console.log(arr);
      console.log(arr.toString());
Copy the code

Back to directory ↑

function

Definition of a function

  • General function writing (Create a new Js file and write the following functions)
  1. Write a function that determines whether a number isOdd (isOdd)

  2. Write a function that determines whether a number isPrime

  3. Write a function that sums sumOfArray over an array

  4. Write a function that gets the maximum value in an array, maxOfArray

  5. Write a function that gets the minimum value minOfArray in an array

  6. Write a function that determines whether an array is a sparse hasEmptyInArray

  7. Write a function to determine whether the year is a leap year, isLeap

  8. Write a function to get getDays, the number of days in a month in a year

  9. Write a function to get the most common number in an array and the frequency of occurrence getTopFreqInArray

/** * check whether a number is odd *@param  {number}  
 * @return {Boolean}    * /
function isOdd(num) {
  return num % 2! = =0;
}
/** * check whether a number is prime *@param {number} [*@return {Boolean} * /
function isPrime(num) {
  if (num < 2)
    return false;
  for (var i = 2; i < num; i++) {
    if (num % i === 0)
      return false;
  }
  return true;
}
/** * sum over an array *@param {array} 
 * @return {number}* /
function sumOfArray(arr) {
  var sum = 0;
  for (var i = 0; i < arr.length; i++) {
    sum += arr[i];
  }
  return sum;
}
/** * gets the maximum value in the array *@param  {arr} 
 * @return {number}    * /
function maxOfArray(arr) {
  if (arr.length === 0) {
    return;
  }
  var max = arr[0]
  for (var i = 1; i < arr.length; i++) {
    max = arr[i] > max ? arr[i] : max;
  }
  return max;
}

/** * returns the smallest value in the array *@return {array} 
 * @return {number}* /
function minOfArray(arr) {
  if (arr.length === 0) {
    return;
  }
  var min = arr[0];
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] < min) {
      min = arr[i]
    }
  }
  return min;
}
/** * check if an array is sparse *@param  {arr}
 * @return {Boolean}  * /
function hasEmptyInArray(arr) {
  for (var i = 0; i < arr.length; i++) {
    if(! (iin arr)) {
      return true; }}return false;
}

/** * Determines whether the given year is a leap year *@param  {*}
 * @return {Boolean}    * /
function isLeap(year) {
  return year % 4= = =0 && year % 100! = =0 || year % 400= = =0;
}
/** * get the number of days **@param {*} Years *@param {*} *@return {*} Number of days * /
function getDays(year, month) {
  return new Date(year, month, 0).getDate();
}

/** * returns the most frequent number and frequency in the array *@param  {Array} 
 * @return {Object}    * /
function getTopFreqInArray(arr) {
  var records = {}
  for (var i = 0; i < arr.length; i++) {
    if(records[arr[i]]) {
      records[arr[i]]++;
    } else {
      records[arr[i]] = 1; }}var result = {
    number:undefined.frequency:undefined
  }
  var result;
  for(var prop in records) {
    if(! result || records[prop] > result["frequency"]) {
      result["number"] = +prop;
      result["frequency"] = records[prop]; }}return result;
}
Copy the code
  • Use of functions
  • Goldbach’s conjecture is realized by using some of the above functions

Any even number greater than 2 can be rewritten as the sum of two primes, allowing the user to input an integer greater than 2 and output the sum of the two primes

function begin() {
  var num = +prompt("Please enter an even number greater than 2.");
  if (isNaN(num) || isOdd(num) || num <= 2) {
    console.log("Input error");
    return;
  } else {
    for (var i = 2; i < num - 1; i++) {
      var j = num - i;
      if (isPrime(i) && isPrime(j) && i <= j) {
        console.log(`${num} = ${i} + ${j}`); }}}}Copy the code
  • Let the user enter a year and output the number of days per month in that year
begin();
function begin() {
  var year = +prompt("Please enter a year between 1990 and 2100.")
  if (isNaN(year) || year < 1990 || year > 2100) {
    console.log('Input illegal');
  } else {
    for (var m = 1; m <= 12; m++) {
      console.log(`${year}years${m}Month:${getDays(year,m)}Day `); }}}Copy the code

Back to directory ↑

Function expressions and this

  • What does the following program output
function f1() {
  var arr = [];
  var a = 1;
  for (var i = 1; i <= 3; i++) {
    arr.push(function() {
      returni * a++; })}return arr;
}
f1().forEach(function(item) {
  console.log(item()); / / 4 August 12
})
Copy the code
  • What does the following code output
var number = 5; 
var obj = {
  number: 3.fn1: (function () {
    var number;
    this.name *= 2;
    number = number * 2;
    number = 3;
    return function () {
      var num = this.number;
      this.number *= 2;
      console.log(num); / / 5 3
      number *= 3;
      console.log(number); / / September 27}}}) ()var fn1 = obj.fn1;
fn1.call(null);
obj.fn1();
console.log(number); / / 10
Copy the code
  • Write a function that sorts an array, taking into account all possible sorts of the array
  function sort(arr, callback) {
    if(! callback) { callback =function(a, b) {
        if (a > b) {
          return 1
        } else if (a === b) {
          return 0
        } else {
          return -1; }}}for (var i = 0; i < arr.length - 1; i++) {
      for (var j = 0; j < arr.length - 1 - i; j++) {
        if (callback(arr[j], arr[j + 1) >0) {
          var temp = arr[j];
          arr[j] = arr[j + 1];
          arr[j + 1] = temp; }}}}Copy the code
  • Write a function to filter an array based on the specified criteria
  function filter(arr, callback) {
    var newArr = [];
    for (var i = 0; i < arr.length; i++) {
      if(callback(arr[i], i)) { newArr.push(arr[i]); }}return newArr;
  }

Copy the code
  • Write a function that returns find, the first element in an array that meets the specified criteria
  function find(arr, callback) {
    for (var i = 0; i < arr.length; i++) {
      if (callback(arr[i], i)) {
        returnarr[i]; }}return;
  }
Copy the code
  • Write a function that returns count, the number of elements in an array that meet the specified criteria
   function count(arr, callback) {
    var num = 0;
    for (var i = 0; i < arr.length; i++) {
      if(callback(arr[i], i)) { num++; }}return num;
  }

Copy the code

Back to directory ↑

The constructor

  • Heroes play monster games

Heroes and monsters have damage, defense, health, and crit chance (double damage on crit).

Attack Damage = Attack Power – Defense

Damage is at least 1

Create a hero and a monster and have them attack each other until one of them dies, exporting the entire attack

      /** * Game character constructor *@param {*} Name Role name *@param {*} Attack power *@param {*} Defence *@param {*} HP Health *@param {*} CritRate critRate (0-100) */
      function Charactor(name, attack, defence, hp, critRate) {
        this.name = name;
        this.attack = attack;
        this.defence = defence;
        this.hp = hp;
        this.critRate = critRate;
        /** * Prints information */
        this.print = function() {
          console.log(`The ${this.name}\t Health:The ${this.hp}\ T Attack power:The ${this.attack}\t Defense:The ${this.defence}\t Crit rate:The ${this.critRate}% `);
        }
        /** * attack *@param  {*} Ctor Attacked character */
        this.hit = function(ctor) {
          var damage = this.attack - ctor.defence;
          // Determine if there is a critical hit
          var isCrit = false;
          var ran = Math.random();
          if (ran <= this.critRate / 100) {
            damage *= 2;
            isCrit = true;
          }
          // Damage is at least 1
          if (damage < 1) {
            damage = 1;
          }

          ctor.hp -= damage;
          // Have at least 0 health
          if (ctor.hp < 0) {
            ctor.hp = 0;
          }
          console.log(`${isCrit?'critical strike! ':' '}The ${this.name}"Attack"${ctor.name}】,${damage}Point damage, the opponent's current health is${ctor.hp}`);

          // Returns whether the other party is dead
          return ctor.hp === 0; }}var hero = new Charactor("Hero".100.20.500.30);
      var monster = new Charactor("Monster".120.40.400.5);
      hero.print();
      console.log('vs');
      monster.print();

      console.log('------------- Game on ----------------------');
      while (true) {
        if (hero.hit(monster)) {
          break;
        }
        if (monster.hit(hero)) {
          break; }}console.log('= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =');
      hero.print();
      monster.print();
      console.log('---------------- Game over -------------------');
Copy the code

Back to directory ↑

recursive

  • Hannotta problem
function hannuo(n1, n2, n3, n) {
  if (n === 1) {
    console.log(`${n1}--->${n3}`);
  } else {
    hannuo(n1, n3, n2, n - 1);
    console.log(`${n1}--->${n3}`);
    hannuo(n2, n1, n3, n - 1);
  }
}
hannuo('A'.'B'.'C'.4);
Copy the code

Back to directory ↑

Execute context and scope chains

  • Draw the following code scope chain

Knowledge tips

VO contains an additional attribute that points to the function that created it. Each function is created with a hidden attribute [[scope]] that points to the AO at the time the function was created

  • Draw a picture to understand the problem

1. Draw the following code scope chain

      var g = 0;
      function A() {
        var a = 1;
        function B() {
          var b = 2;
          var C = function() {
            var c = 3;
            console.log(c, b, a, g);
          }
          C();
        }
        B();
      }
      A();
Copy the code

2. Draw the following code scope chain, with closures formed

    function A() {
      var count = 0;
      return function() {
        count++;
        console.log(count); }}var test = A();
    test();
    test();
    test();
    console.log(count);
Copy the code

3. Use closures to let timers print different values

      for (var i = 0; i < 3; i++) {
        (function (i) {
          setTimeout(function () {
            console.log(i);
          },1000);
        })(i)
      }
Copy the code

  • Interview questions (Print out the results and draw a prototype chain diagram)
      var foo = { n: 1 };
      (function(foo) {
        console.log(foo.n); / / 1
        foo.n = 3;
        var foo = { n: 2 };
        console.log(foo.n); / / 2
      })(foo);
      console.log(foo.n); / / 3
Copy the code
      let food = "rice";
      let eat = function() {
        console.log(`eat ${food}`); //eat rice
      };
      (function() {
        let food = "noodle"; eat(); }) ();Copy the code
      var food = "rice";
      (function () {
        var food = "noodle";
        var eat = function () {
          console.log(`eat ${food}`);
        };
        eat(); //eat noodle}) ();Copy the code
      function A() {
        for (i = 0; i < 10; i++) {
          setTimeout(function() {
            console.log(i); // Prints 10 10s
          }, 1000)
        }
      }
      A();
      console.log(i); / / 10
Copy the code

Back to directory ↑

Essence of scope chain exercises

console.log(a)    //undefined
var a = 12
function fn() {
    console.log(a) //undefined
    var a = 13
}
fn()
console.log(a) / / 12

Copy the code
console.log(a) //undefined
var a = 12
function fn() {
    console.log(a) / / 12
    a = 13
}
fn()
console.log(a) / / 13

Copy the code
console.log(a) / / an error
let a = 12
function fn() {
    console.log(a) 
    let a = 13
}
fn()
console.log(a) 

Copy the code
console.log(a) / / an error
a = 12
function fn() {
    console.log(a)
    let a = 13
}
fn()
console.log(a)

Copy the code
var foo = 1
function bar() {
    if(! foo){var foo = 10
    }
    console.log(foo) / / 10
}

bar();
Copy the code
var foo = 1
function bar() {
    if(! foo){ foo =10
    }
    console.log(foo) / / 1
}

bar()

Copy the code
var n=0
function a() {
    var n = 10
    function b() {
        n++
        console.log(n) / / 11
    }
    b()
    return b
}

var c=a()
c()  / / 12
console.log(n); / / 0

Copy the code
var a=10
var b=11
var c=12

function test(a){
    a = 1
    var b = 2
    c = 3
}
test(100)

console.log(a) / / 10
console.log(b) / / 11
console.log(c) / / 3

Copy the code
if(! ('a' in window)) {var a = 10
}
console.log(a) //undefined

Copy the code
var a = 4
function b(x, y, a) {
    console.log(a) / / 3
    arguments[2] = 10
    console.log(a) / / 10
}
a = b(1.2.3);
console.log(a) //undefined

Copy the code
var a = 9
function fn() {
    a = 0
    return function(b){
        return b+a++
    }
}

var f=fn() 
console.log(f(5))   / / 5
console.log(fn()(5))/ / 5
console.log(f(5)) / / 6
console.log(a)   / / 2

Copy the code
var ary = [1.2.3.4]
function fn(ary){
    ary[0] = 0
    ary = [0]
    ary[0] = 100

    return ary
}
var res = fn(ary)
console.log(ary)  / / [0, 2, 3, 4]
console.log(res)  / / [100]

Copy the code
function fn(i){
    return function(n){
        console.log(n + (i++)); }}var f = fn(10)
f(20) / / 30
fn(20) (40) / / 60
fn(30) (50) / / 80
f(30) / / 41

Copy the code
var num = 10;
var obj = {num: 20};
obj.fn = (function(num){
   this.num = num * 3
   num++
   return function (n) {
       this.num += n;
       num++;
       console.log(num);
   }
})(obj.num);
var fn = obj.fn
fn(5) / / 22
obj.fn(10) / / 23
console.log(num, obj.num) / / 65, 30

Copy the code
var fullName = 'language'
var obj = {
    fullName: 'javascript'.prop: {
        getFullName: function() {
            return this.fullName
        }
    }
}
console.log(obj.prop.getFullName()) //undefined
var test = obj.prop.getFullName
console.log(test()) //language

Copy the code
var name = 'window'
var Tom = {
    name: "tom".show: function() {
        console.log(this.name)
    },
    wait: function() {
        var fun = this.show
        fun()
    }
}
Tom.wait() //window

Copy the code

Back to directory ↑

String object

  • Returns the number of occurrences of substring in string STR

Incoming: “abcabcabc”, “ABC”; Returns: 3

function searchSub(string, sub) {
    var i = 0;
    var len = sub.length;
    var count = 0;
    while((i = string.indexOf(sub, i)) ! = = -1) {
    i += len;
    count++;
    }
    return count;
}
Copy the code
  • Inverts a three-digit integer
 // Use the reverse method on arrays
 function reverseNum(num) {
   if (isNaN(num) || Math.abs(num) < 100 || Math.abs(num) > 999) {
     return;
   }
   var sign = Math.sign(num);
   var numAbs = Math.abs(num);
   return +(numAbs.toString().split(' ').reverse().join(' ')) * sign;
 }
 // Method 2:
 function reverseNum(num) {
   if (isNaN(num) || Math.abs(num) < 100 || Math.abs(num) > 999) {
     return;
   }
   var sign = Math.sign(num);
   var numAbs = Math.abs(num);
   var total = 0;
   while(numAbs) {
     total = total * 10 + numAbs % 10;
     numAbs = Math.floor(numAbs / 10);
   }
   return total * sign;
 }
 console.log(reverseNum(+prompt()));
Copy the code
  • Given a string object in which English words are separated by various non-alphabetic characters, count the number of words passed in:'Yes,she**is%%my@love.'
      var str = 'Yes,she**is%%my@love.';
      console.log(total(str));
      // Replace a contiguous non-alphabetic character with a space character, remove the first and last Spaces, and then delimit the array with Spaces.
      // Return the length of the array
      function total(str) {
        var len = str.length;
        str = str.replace(/[^a-zA-Z]+/g.' ').trim();
        return str.split(' ').length;
      }

      / / method 2
      function total(str) {
        var len = str.length;
        var reg = /[a-zA-Z]/;
        var count = 0;
        var newArr = [];
        var firstIndex = 0;
        for (var i = 0; i < len; i++) {
          if (reg.test(str[i])) {

          } else {
            count++;
            newArr.push(str.substring(firstIndex, i));
            firstIndex = i + 1;
            while(! reg.test(str[firstIndex]) && i < len) { i++; firstIndex++; }}}return newArr.length;
      }
Copy the code
  • Find the most common letter in the string

Concatenate the letter and the number of occurrences into a new string, returning the new string passed in :’WelcomeToQianfeng’; Return: ‘e3’; (Written as a function)

      
      var str = 'WelcomeToHeiMa';
      console.log(count(str));

      // Method 1: Sort the array by character code, choose ------> Quantity value ------> character
      function count(str) {
        var index = 0;
        var result = [];
        var arr = str.split(' ').sort();
        for (var i = 0; i < arr.length; i++) {
          if(result.indexOf(arr[i]) === -1) {
            index = 0;
            result[index] = arr[i];
          } else{ result[++index] = arr[i]; }}return result.length + result[result.length - 1];
      }

      // Method 2: statistics key ------> quantity value ------> characters find the number of occurrences of each character, and store the corresponding position in the array
      function count(str) {
        var arr = [];
        for (var i = 0; i < str.length; i++) {
          var fread = 0;
          var j = 0;
          while((fread = str.indexOf(str.charAt(i), fread)) ! = = -1) {
            fread++;
            j++;
          }
          arr[j] = str.charAt(i);
        }
        return arr.length - 1 + arr[arr.length - 1];
      }

Copy the code

Back to directory ↑

The Array object

  • Var arr = [6, 1, 2, 3, 4, 5, 6].

Remove the negative numbers from the array, square each term, double each term, and sum without loops

var arr = [1.2.3.4.5.6, -1, -2, -3, -4, -5, -6];
var sum = arr.filter(function(item) {
  return item >= 0;
}).map(function(item) {
  return item * item * 2;
}).reduce(function(s, item) {
  return s + item;
}, 0);
console.log(sum);
Copy the code

Back to directory ↑

Primitive type wrapper

  • Find the most common character in a string, the print character, and the number of occurrences
      // New characters are stored at the beginning of the array, and non-new characters are stored later
      // The last character that is not overwritten is the character that occurs most often
      function count(str) {
        var temp = str.split(' ').sort();
        var result = [];
        for (var i = 0; i < temp.length; i++) {
          if (result.includes(temp[i])) {
            result[++count] = temp[i];
          } else {
            var count = 0; result[count] = temp[i]; }}console.log(result.length + result[result.length - 1]);
      }
Copy the code
  • Remove Spaces between words in a string and capitalize each word
      var str = 'my name is liu\tchao\nhow are you';
      console.log(bigCamel(str));
      console.log(bigCamel2(str));

      // The first method
      function bigCamel(str) {
        var temp = str.split(/[\n\s\t]+/g);
        var res = temp.map(function(item) {
          return item[0].toUpperCase() + item.substring(1);
        });
        return res.join(' ');
      }

      // The second method
      function bigCamel2(str) {
        var empties = ' \n\r\t';
        var res = ' ';
        for (var i = 0; i < str.length; i++) {
          if(! empties.includes(str[i])) {if(! empties.includes(str[i -1]) && i ! = =0) {
              res += str[i];
            } else{ res += str[i].toUpperCase(); }}}return res;
      }
Copy the code
  • Write a function that generates a random string of specified length, containing only upper – and lower-case letters, digits, and other characters
    console.log(getRandomString(10))

    function getRandomString(len) {
      var template = ' ';
      for (var i = 97; i < 97 + 26; i++) {
        template += String.fromCharCode(i);
      }
      for (i = 65; i < 65 + 26; i++) {
        template += String.fromCharCode(i);
      }
      for (i = 48; i < 48 + 10; i++) {
        template += String.fromCharCode(i);
      }
      var res = ' ';
      for (i = 0; i < len; i++) {
        var index = MyFunctions.getRandom(0, template.length - 1);
        res += template[index];
      }
      return res;
    }
Copy the code
  • Reorder a string in ascending order in the character encoding order
    var str = 'adjfkgjiedkj';
    var newStr = str.split(' ').sort().join(' ');
    console.log(newStr);
Copy the code
  • Take the user’s birth year, month, date and gender from a standard ID number and store them in the object
    var pid = '420114199609210533';
    console.log(getInfoFromPID(pid));

    function getInfoFromPID(pid) {
      return {
        birthdayYear: +pid.substr(6.4),
        birthdayMonth: +pid.substr(10.2),
        birthdayDay: +pid.substr(12.2),
        gender: pid[pid.length - 2] % 2= = =0 ? 'woman' : 'male'}}Copy the code

Back to directory ↑

The Date object

  1. Gets the number of days in a month

Method one:

    function getDays(year, month) {
        return new Date(year, month, 0).getDate();
    }
Copy the code

Method 2:

  function getDays(year, month) {
      var days = [31.28.31.30.31.30.31.31.30.31.30.31];
      // Check if it is a leap year
      var isLeap = year % 4= = =0 && year % 100! = =0 || year % 400= = =0;
      if (month === 2) {
        return isLeap ? days[month - 1] + 1 : days[month - 1];
      }
      return days[month - 1];
  }
Copy the code
  1. Gets the date in the specified format

  2. Calculate age according to date of birth

function getAge(year, month, date) {
    var now = new Date(a);var nowYear = now.getFullYear();
    var age = nowYear - year;
    month -= 1;
    var isLeap = nowYear % 4= = =0 && nowYear % 100! = =0 || nowYear % 400= = =0;
    if (month === 1 && date === 29 && !isLeap) {
    month = 28;
    }
    var thisYearBirthday = new Date(nowYear, month, date);
    if (now < thisYearBirthday) {
    age--;
    }
    return age;
}
Copy the code
  1. Calculate the number of days until your birthday based on your birth date
  function getbirthday(month, date) {
    var now = new Date(a);var nowYear = now.getFullYear();
    var thisYearBirthday = new Date(nowYear, month - 1, date);
    if (now > thisYearBirthday) {
      // This year's birthday, even if the distance from next year's birthday
       thisYearBirthday.setFullYear(nowYear + 1);
    }
    return Math.ceil((thisYearBirthday.getTime() - now.getTime()) / 1000 / 3600 / 24);
  }
Copy the code
  1. Print the day of the week for a given month
  function getdays(year, month) {
    var dateObj = new Date(year, month - 1);
    var week = ['day'.'一'.'二'.'三'.'four'.'five'.'六'
    ];
    // 1. Find the number of days in a given month
    var days = new Date(year, month, 0).getDate();
    // 2. Circularly print every day of the week
    for (var i = 0; i < days; i++) {
      dateObj.setDate(i + 1);
      console.log(`${year}years${month}month${i+1}Week day:${week[dateObj.getDay()]}`)}}Copy the code

Back to directory ↑

Regular expression

  • Write a regular expression to match a string and get the number of matches and the structure of the matches
    var str = '123sldfjf43435djfd124dfkdj888jfdkjf136';
    var reg = /\d{3}/g;
    var res = ' ',
      result = ' ',
      count = 0;
    while (res = reg.exec(str)) {
      result += (res[0] + '\n');
      count++;
    }
    console.log(Matching the `${count}The matching string is :\n${result}`);
Copy the code
  • Gets the number of Chinese characters in a string
    var str = 'Army resists Akjfdkfjjf hotel service winds cool down';
    var count = 0,
      reg = /[\u4e00-\u9fa5]/g
    while (reg.exec(str)) {
      count++;
    }
    console.log(count);
Copy the code
  • Filter sensitive words, there is a sensitive phrase, need to replace the occurrence of sensitive words in the string with* * * *
    var senWords = ['Communist party'.'violence'.'Lu Benwei'.'Trade war'];
    var str = 'Skin communist ajDF violence violence violence DKFJ Lubenwei JJFD Trade war GGDFJ file';
    console.log(removeSensitiveWord(str, '* * * *'));
    // Dynamically generate regular expressions
    / / (' communist '|' violence '|' lubumbashi wei '|' trade ') +

    function removeSensitiveWord(str, rep) {
      var reg = new RegExp(` (${senWords.join('|')}) + `.'g');
      return str.replace(reg, function ($) {
        returnrep; })}Copy the code
  • Judge password strength

Passwords must contain lowercase letters, uppercase letters, digits, and special characters (! @ # _.). Six to twelve

/ ^ (? =.*[a-z]+)(? =.*[A-Z]+)(? * [=.0-9(] +)? =. * [! @ # _,] +) {6.12} $/Copy the code
  • Judge password strength
The password must be 6 to 12 characters in length including lowercase letters, uppercase letters, digits, special characters' (! @ # _.). 'Strong lowercase letters, uppercase letters, lowercase letters in digits, uppercase letters light others do not meet the requirementsCopy the code
    var str = prompt('Please enter your password');
    if (/ ^ (? =.*[a-z]+)(? =.*[A-Z]+)(? =. * ([0-9] +)? =. * [! @ # _,] +). 6, 12 {} $/.test(str)) {
      alert('Strong password');
    } else if (/ ^ (? =.*[a-z]+)(? =.*[A-Z]+)(? =. * [0-9] +). 6, 12 {} $/.test(str)) {
      alert('Password strength in progress');
    } else if (/ ^ (? =.*[a-z]+)(? =. * [a-z] +). 6, 12 {} $/.test(str)) {
      alert('Light password strength');
    } else {
      alert('Not meeting the requirements');
    }
Copy the code

Back to directory ↑

Es6

Arrow function

  • The this below points to
    var obj = {
      name: 'lily'.fun: function() {
        return (() = > this.name)()
      },
      fn: () = > this.name
    };
    name = 'lucy';
    console.log(obj.fn());//lucy
    console.log(obj.fun());//lilyArrow functions are typically used as callback functionsCopy the code

Array extension

  • Use filter to deduplicate the array
    var x = ['a'.'a'.'b'.'b'.'c'.'b'.'a'];
    var y = x.filter(function(item, index) {
      if (x.indexOf(item) == index) {
        returnitem; }});console.log(y)
Copy the code
  • Use reduce to deduplicate the array
/ / method
    var x = ['a'.'a'.'b'.'b'.'c'.'b'.'a'];
    var y = x.reduce(function(arr, item, index) {
      if (x.indexOf(item) == index) {
        arr.push(item)
      }
      returnarr; } []);console.log(y);
/ / method 2
    var y = x.reduce(function(arr, a, b) {

      if(! arr.includes(a)) { arr.push(a); }return arr;
    }, [])
    
Copy the code
  • Count the number of items in the array with reduece
    var x = ['a'.'a'.'b'.'b'.'c'.'b'.'a'];
    var y = x.reduce(function(obj, item) {
      if (item in obj) {
        obj[item]++;
      } else {
        obj[item] = 1;
      }
      return obj
    }, {});
    console.log(y);

Copy the code
  • Flatten the array with reduce