On weekdays, I will summarize the front-end knowledge points in the process of project development together. When I come back a year later, I will thank myself for my efforts.


Question 1Js prints 1,2,3,4,5 every second

Method 1: self-executing functions

for (var i=0; i<5; i++) {
  / / closures
  (function (i) {
    setTimeout(() = > console.log(i), 1000*i)
  })(i)
}
Copy the code

Method 2: ES6 block-level scoped let

for (let i=0; i<5; i++) {
  (function () {
    setTimeout(() = > console.log(i), 1000*i)
  })()
}
Copy the code

Method three: address passing

var out = (i) = > {
  setTimeout (() = > console.log(i), 1000*i)
}
for (var i=0; i<5; i++) {
  out(i)
}
Copy the code

Method 4: promise.all (

var arr = []
var output = (i) = > new Promise(res= > {
  setTimeout(() = >{
    console.log(i)
    res()
  }, 1000*i)
})
for (var i=0; i<5; i++) {
  arr.push(output(i))
}
Promise.all(arr).then(() = > console.log(5))
Copy the code

Method 5: Async await method

var sleep = () = > new Promise (res= > setTimeout(res, 1000))
async function count () {
  for (let i=0; i<5; i++) {
    await sleep()
    console.log(i)
  }
}
count()
Copy the code
function sleep(){
  return new Promise((resolve) = >{
    setTimeout(resolve,1000); })}async function count(){
  for(let i=0; i<5; i++){await sleep();
    console.log(i)
  }
}
count()
Copy the code

Methods 6: setInterval

function count(num, time) {
  var i = 0;
  var fn = setInterval(function () {
    console.log(i++);
    if (i >= num) {
      clearInterval(fn);
    }
  }, time * 1000);
}
count(5.1);
Copy the code

Second questionUse animation to create a text mask animation effect

 h1{
  font-size:60px;
  background: url(bg.jpg) repeat;
  -webkit-background-clip:text;
  -webkit-text-fill-color:transparent;
  animation:fn 5s alternate infinite;
}
@keyframes fn{
  0%{
      background-position:0px 0px;
  }
  20%{
      background-position:30% 0px;
  }
  50%{
      background-position:50% 0px;
  }
  70%{
      background-position:70% 0px;
  }
  100%{
      background-position:100% 0px; }}Copy the code

The third questionThe title is gradient and the color changes consistently

.title{
  color: #f35626;
  background-image: linear-gradient(92deg.#f35626 0%.#feab3a 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: hue 60s infinite linear;
}

@keyframes hue {
  from {
    filter: hue-rotate(0deg);
  }
  
  to {
    filter: hue-rotate(-360deg); }}Copy the code

Number 4Most of thetext-fill-colorattribute

Text-fill-color sets the fill color of the specified text. If both and are set, the color defined by < text-fill-color > will override the < color > attribute

Note: A background-clip must be placed after a background otherwise it will not work. A background-clip is used because a text-fill-color cannot use linear.

Background-clip: Text clipped the background as the text area.

Text-fill-color can implement gradient font and hollow font, as follows:

Gradient font
<p class="font1">Hello, this is my gradient font</p>
Copy the code
.font1{
  font-size:22px;
  background-image: -webkit-linear-gradient(bottom, red, blue);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  display:inline-block; // Apply all to the font for gradient}Copy the code
Hollow out the font
.font1{
  font-size:32px;
  -webkit-text-fill-color: transparent;
  -webkit-text-stroke:1px # 000;
 }
Copy the code

5CSS3 Filter details (change blur brightness transparency and other methods)

The CSS3 Filter property provides the ability to blur and change the color of an element. CSS3 Fitler is often used to adjust the rendering, background, or border display effect of an image.

– Webkit-filter is an attribute of CSS3. Webkit supports these functions first

The effects currently supported in the specification are:

  • grayscaleThe gray value is a decimal between 0 and 1
  • sepiaThe brown values are decimal points between 0 and 1
  • saturateThe saturation value is num
  • hue-rotateHue rotation value is Angle
  • invertInvert values are fractions between 0 and 1
  • opacityThe transparency value is a decimal between 0 and 1
  • brightnessThe brightness value is a decimal between 0 and 1
  • contrastThe contrast value is num
  • blurThe fuzzy value is length
  • drop-shadowshadow

The demo to see

  1. The fuzzy
-webkit-filter: blur(9px);
filter: blur(9px);
Copy the code
  1. gray
-webkit-filter: grayscale(1);
filter: grayscale(1);
Copy the code
  1. brightness
-webkit-filter: brightness(2.3);
filter: brightness(2.3);
Copy the code
  1. contrast
-webkit-filter: contrast(4.4);
filter: contrast(4.4);
Copy the code
  1. saturation
-webkit-filter: saturate(3.6);
filter: saturate(3.6);
Copy the code
  1. Hue rotation
-webkit-filter: hue-rotate(185deg);
filter: hue-rotate(185deg);
Copy the code
  1. The color
-webkit-filter: invert(1);
filter: invert(1)
Copy the code
  1. shadow
-webkit-filter: drop-shadow(0px 0px 5px # 000);
filter: drop-shadow(0px 0px 5px # 000);
Copy the code
  1. transparency
-webkit-filter: opacity(55%);
filter: opacity(55%);
Copy the code
  1. brown
-webkit-filter: sepia(0.77);
filter: sepia(0.77);
Copy the code

Number 6 JSON.stringify(value[, replacer [, space]])

  • value

The value to be serialized into a JSON string.

This is the first parameter, and it should be familiar, and it’s the most common one. You barely need the other two.

You usually pass in an object. But more than that, you can pass in other values.

  • Replacer | is optionalThere are three types of values:
    • Function that transforms and processes each attribute of the serialized value during serialization
    • Array, and only the property names contained in this array will be serialized into the final JSON string
    • Null or not provided, all attributes of the object are serialized

Under normal circumstances, we do not pass, according to the third way.

  • Space | is optional

Specifies a blank string for indentation to beautify the output.

There are three types of values that can be specified:

  • Number, representing how many Spaces there are. The upper limit is 10, and any value less than 1 means no Spaces.
  • String, the first ten letters of the string, which will be used as Spaces.
  • Null or not provided, there will be no Spaces.

Under normal circumstances, we do not pass, according to the third way.

Return value A JSON string representing the given value.

Question 7The delete operator returns a Boolean value: true for successful deletion, false otherwise.

const name = "Lydia";
age = 21;

console.log(delete name);
console.log(delete age);
// false true
Copy the code

The delete operator returns a Boolean value: true for successful deletion, false otherwise. However, variables declared by the var, const, or let keywords cannot be deleted using the DELETE operator.

The name variable is declared by the const keyword, so deletion failed: return false. And when we set age to 21, we’re actually adding a property called age to the global object. Properties in objects can be deleted, as can global objects, so delete Age returns true.

Question 9Import imported modules are read-only: you cannot modify imported modules

// counter.js
let counter = 10;
export default counter;

// index.js
import myCounter from "./counter";
myCounter += 1;
console.log(myCounter);
// Printed value: Error
Copy the code

Imported modules are read-only: you cannot modify imported modules. Their values can only be modified by exporting their modules.

When we add a value to myCounter we throw an exception: myCounter is read-only and cannot be modified.

Question 10Passing assignments of values and objects


function getInfo(member, year) {
  member.name = "Lydia";
  year = "1998";
}

const person = { name: "Sarah" };
const birthYear = "1997";

getInfo(person, birthYear);

console.log(person, birthYear);
// A: { name: "Lydia" }, "1997"
Copy the code

Unlike ordinary parameters, which are passed by value, objects are passed by reference. So birthYear is value passed because it is a string rather than an object. When we pass a value to a parameter, a copy of that value is created.

The birthYear variable has a reference to “1997” and the passed parameter also has a reference to “1997”, but the references are not the same. When we update the value of year by assigning “1998” to it, we are simply updating year. BirthYear is still “1997” at this point.

And person is an object. The member argument refers to the same object. When we modify the attributes of the object referenced by member, the corresponding attributes of person are also modified because they refer to the same object, and the name attribute of person becomes “Lydia”.

Question 11Usage of nextTick in VUE

A deferred callback is performed after the next DOM update cycle. Use this method immediately after modifying the data to get the updated DOM

VUE asynchronous update queue: VUE is updated by data-driven view, and the update process is asynchronous. That is, Vue opens a queue (officially called an asynchronous update queue by Vue) when the data it listens to changes to you. Views need to wait for all data changes in the queue to complete before they are uniformly updated

Personal understanding: You need to operate on the new view after the view is updated.

  • Get the updated DOM
  • If you want to increated()The created() hook function does not render the DOM yet, so it cannot directly manipulate the DOM. Instead, the created() hook function uses $nextTick()
  • When you want to use JS to operate on a new view after updating the data
  • This is used when using third-party plug-ins that require the DOM to change dynamically and then reapply the plug-in$nextTick()To reapply the plug-in’s methods

Since $nextTick() returns a Promise object, we could do the same thing with async/await syntax:

<div id="myApp">
    <input type="button" value="Click on me." @click="changeStr">
    <p ref="myP">{{str}}</p>
</div>
<script>
    new Vue({
        el:"#myApp".data: {str:"Initialize content!"
        },
        methods: {changeStr(){
                this.str = "Changed!";
                // Initialize the content!
                console.log(this.$refs.myP.innerText)
            },
            changeStr(){
              this.str = "Changed!";
              // We can get the updated DOM with $nextTick()
              this.$nextTick(() = >{
                  // Output result: I love you China, my dear mother!
                  console.log(this.$refs.myP.innerText);
              });
              this.str = "I love you China, my dear mother!"
            },
            changeStr3:async function(){
                this.str = "Changed!";
                this.str = "I love you China, my dear mother!"
                await this.$nextTick();
                console.log(this.$refs.myP.innerText);
            },
            changeStr4(){
                this.str = "Changed!";
                this.$nextTick().then(() = >{
                    // Output result: I love you China, my dear mother!
                    console.log(this.$refs.myP.innerText);
                });
                this.str = "I love you China, my dear mother!"}}})</script>
Copy the code
<div id="app">
  <input ref="input" v-show="inputShow">
  <button @click="show">show</button>  
 </div>

export default { 
 data() {
   return {
     inputShow: false
   }
  },
  methods: {
    show() {
      this.inputShow = true
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    }
  }
}
Copy the code

Number 12The amount is in thousands with 2 decimal places reserved

export function toThousandFilter(num) {
  if(! num) {return ' '
  }
  return (+num).toFixed(2).replace(/(\d)(? =(\d{3})+\.) /g.'$1'); // Add a ',' to every third number using a regular substitution;
  // return (+num || 0).toString().replace(/^-? \d+/g, m => m.replace(/(? = (? ! \b)(\d{3})+$)/g, ','))
}
Copy the code

13 questionsVue defined filter

import * as filters from './filters' // global filters
// register global utility filters
Object.keys(filters).forEach(key= > {
  Vue.filter(key, filters[key])
})
Copy the code

Question 14Input [file] Android cannot drop the camera

When writing , you can successfully drop the photo and gallery blocks on ios. On Android phones, you can only call the gallery, but not the photo function

Workaround: Add accept to input and capture=’camera’ to capture, without library functionality

<input type="file" accept="iamge/*" capture="camera">/ / camera<input type="file" accept="video/*" capture="camcorder">/ / video<input type="file" accept="audio/*" capture="microphone">/ / audioCopy the code

Note: Capture indicates that you can capture the default system devices, such as camera camera, Camcorder camera, and microphone recording.

Question 15The difference between Apply, call, and bind in javascript

In JS, all three are used to change the orientation of a function’s this object.

Similarities among the three:

  1. Both are used to change the orientation of the function’s this object.
  2. The first argument is always the object to which this refers.
  3. Can be passed by subsequent parameters.

The difference between the three:

  1. Call and apply are for functionsDirect callAnd the bind methodIt still returns a function, so you need () to call it later
  2. The arguments after call correspond one to one in the method, and the second argument to apply is an array
  3. Bind can pass arguments just like call and can pass arguments at the time of the call
var xw = {
  name : "Wang".gender : "Male".age : 24.say : function(school,grade) {
          alert(this.name + "," + this.gender + "This year" + this.age + "In the" + school + "On"+ grade); }}var xh = {
  name : "Little red".gender : "Female".age : 18
}
// This is true for call
xw.say.call(xh,"Experimental primary School"."Sixth grade");  
// This is true for apply
xw.say.apply(xh,["Experimental primary School"."Sixth grade"]);     
/ / to bind the parameter
xw.say.bind(xh,"Experimental primary School"."Sixth grade") (); xw.say.bind(xh)("Experimental primary School"."Sixth grade");
Copy the code

Number 16ParseInt returns only the first character in the string

const num = parseInt("7" x 6".10);
// num = 7
Copy the code

Only the first character of the string is returned. After setting the base (the second parameter, which specifies the base of the number to parse: decimal, 16, octal, binary, etc.) ,parseInt checks whether characters in a string are valid. On encountering an invalid character in the specified base, immediately stop parsing and ignore all subsequent characters.

* is an illegal numeric character. So only “7” is parsed, and the decimal value of 7. Num is 7.