Category Archives: JavaScript

After installing NPM, NRM LS reports an error throw new err_INVALID_ARG_TYPE(name, ‘string‘, value)

Error screenshot:

error screenshots are seen in the cli. Js file line 17 error,

According to the path to find the file:
open files found an error line 17, note down the original 17 rows instead as shown in figure:

//const NRMRC = path.join(process.env.HOME, '.nrmrc');(Note these codes)
const NRMRC = path.join(process.env[(process.platform == 'win32') ?'USERPROFILE' : 'HOME'], '.nrmrc');

After executing CMD, enter NRM ls problem solved

[ERR_INVALID_ARG_TYPE]: The “path“ argument must be of type string. Received undefined error

Start the React project and report the following error:

[ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined
    at validateString (internal/validators.js:120:11)......

There are two possible reasons for this error. The solution is as follows:
The React – Scripts version may be too low. The solution is as follows:

   1. In package.json, replace "react-scripts": "^3.3.0" with
   "react-scripts": "^3.4.0"
   2. Delete the node_modules folder
   3. Run cnpm i for a second

2. Modify the config/webpackDevServer. Config. Js file, as follows:
Look at the config/webpackDevServer. Config. Js files have the following code:

       app.use(noopServiceWorkerMiddleware());

Modified into

app.use(noopServiceWorkerMiddleware('/'));

Done!

JS getting ${pageContext.request.contextPath} Get the root path of the project

As we know, direct access to the JSP EL expression in js is unable to obtain, if you want to get ${pageContext. Request. ContextPath} value, we can use the following two ways:
1, in the ${pageContext. Request. ContextPath} with single quotes, this is the most simple way
2. Create a form with type= “hidden”, for example:

<input name="rootUrl" id="rootUrl" type="hidden" value="${pageContext.request.contextPath}"/>

Then get the value of the form through the JS action:

//Get the project root path
var rootUrl = "";
$(function () {
    rootUrl = $("#rootUrl").val();
})

H5 page left and right stretch content area

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>resize</title>
</head>
<style>
  *,*:before,*:after{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
  }
  body{
    display: flex;
    flex-direction: column;
    align-items: stretch;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
  }
  header,footer{
    flex: none;
    width: 100%;
    height: 60px;
    background: lightgrey;
  }
  footer{
    position: relative;
    background: lightblue;
  }
  .main{
    flex: auto;
    display: flex;
    align-items: stretch;
  }
  .sidebar{
    flex: none;
    width: 200px;
    background: lightgoldenrodyellow;
  }
  .container{
    position: relative;
    flex: auto;
    background: #e0bfc4;
  }
  .resize{
    position: absolute;
    z-index: 100;
    touch-action: none;
  }
  .resize.horizontal{
    top: 0;
    bottom: 0;
    left: 0;
    width: 4px;
    cursor: e-resize;
  }
  .resize.vertical{
    left: 0;
    right: 0;
    top: 0;
    height: 4px;
    cursor: n-resize;
  }
</style>
<body>
  <header>Header</header>
  <section class="main">
    <acticle class="sidebar">Sidebar</acticle>
    <acticle class="container">Content
      <div class="resize horizontal" onmousedown="mousedown('horizontal')"></div>
    </acticle>
  </section>
  <footer>Bottom
    <div class="resize vertical" onmousedown="mousedown('vertical')"></div>
  </footer>
</body>
<script>

function mousedown(flag){
  document.onmousemove = function(){
    // console.log("flag",event,flag)
    if (flag === "horizontal"){
      if (event.x < 200 || event.x > 800) return
      var sidebar = document.querySelector(".sidebar")
      sidebar.style.width = event.x + "px"
    } else if(flag === "vertical"){
      if (event.y < 500 || event.y > 877) return
      var foot =  document.querySelector("footer")
      var top = Number(foot.getBoundingClientRect().top)
      var height = Number(foot.getBoundingClientRect().height)
      foot.style.height = height + top -event.y + "px"
    }
  }
}

document.onmouseup = function(){
  document.onmousemove = null
}

</script>
</html>

JS to determine whether the string contains a character

JS can use to determine whether a string contains another character
String method
1, the indexOf
IndexOf returns the position where the specified string was first found in that character. If it is not found, it returns -1
IndexOf takes two arguments. The first argument is the string to be searched and the second argument is the position to be retrieved

let str = 'abcde';
//For example, search from the third position of str 'a'
console.log(str.indexOf('a',2));// -1
console.log(str.indexOf('a'))// 0

2, lastIndexOf

LastIndexOf takes two arguments, the first is the string to be searched and the second is the position to be retrieved. The default is sting.length-1

let str = 'abcdea';
//For example, search from the third position of str 'a'
console.log(str.lastIndexOf('a',2));// 0
console.log(str.lastIndexOf('a'));// 5

3, includes
The includes() method determines whether a string contains the specified substring and returns true or false
Includes accepts two parameters, the first for the specified string and the second for the lookup location, which defaults to 0

let str = 'abcde';

console.log(str.includes('a'))//true
console.log(str.includes('a',1))//false

4, the match

g: Global search
: Ignoring case
I: The match method retrieving a specified value within a string, or finding a match of one or more regular expressions, returns null if not found (can also be used to query the number of occurrenches of a character in the string)

let str = 'abcdabcda';

console.log(str.match(/a/gi));//['a','a','a']
console.log(str.match(/z/gi));// null

5, the search
The seacrh method is used to retrieve the substring specified in the string, or to retrieve the substring that matches the regular expression, or to return -1 if none

let str = 'abcde';

console.log(str.search('a'));// 0

console.log(str.search(/A/i));//Use regular match to ignore case search Return 0

Regular expression RegExp objects
1. Test method
Retrieves the value specified in the string. Returns true or false.

let str = 'abcdef';

let reg = /A/i;
console.log(reg.test(str));// true

2. Exec method
Retrieves the value specified in the string. Returns the value found and determines its location.
Returns a matching value if there is one in the string, otherwise returns null.

let str = 'abcdef';

console.log(/a/.exec(str))// Return the matching object
console.log(/z/.exec(str))// null

Asynchronous loading method of Baidu map

The purpose of asynchronous loading is to improve the rendering performance of web pages in some scenarios.
Common synchronous loading code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript"
        src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=Your%20key"></script>
    <style>
        html,
        body,
        #map {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>
        var map = new BMapGL.Map('map');
        var point = new BMapGL.Point(116.404, 39.915);
        map.centerAndZoom(point, 10);
        map.enableScrollWheelZoom(true);
    </script>
</body>
</html>

Asynchronous loading method:
idea is to avoid initialization loaded directly, but put the initialization process in the init () function (), for other contents page finished loading, add script tags and callback function calls the init function

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,
        body,
        #map {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>
        function init(){
            var map = new BMapGL.Map('map');
            var point = new BMapGL.Point(116.404, 39.915);
            map.centerAndZoom(point, 10);
            map.enableScrollWheelZoom(true);
        }
        window.onload = function(){
            var script = document.createElement('script')
            script.src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=Your%20key&callback=init"
            document.head.appendChild(script)
        }
        
    </script>
</body>
</html>

CSS text more than 2 lines hidden and show ellipsis

Hide the text beyond two lines and show the ellipsis code as follows:

{
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 2; 
    -webkit-box-orient: vertical;
}

/* Autoprefixer: off */ If you find that two lines of text are displayed but no ellipsis is shown, add the following code:

/* autoprefixer: off */
{
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

ECMAScript arguments object

Function object arguments object
In the functional code, using a special object called arguments, developers can access arguments without explicitly specifying their names.
For example, in the function sayHi(), the first argument is message. This value is also accessible with arguments[0], which is the value of the first argument (the first argument is at position 0, the second argument is at position 1, and so on).
Thus, we can override the function without explicitly naming parameters:

function sayHi() {
  if (arguments[0] == "bye") { return; } alert(arguments[0]); }

Number of test parameters
You can also use the arguments object to detect the number of arguments to a function by referring to the arguments.length property.
The following code prints the number of arguments used per call to the function:

function howManyArgs() {
  alert(arguments.length);
}

howManyArgs("string", 45);
howManyArgs();
howManyArgs(12);

The above code displays “2”, “0”, and “1” in turn.
Note: Unlike other programming languages, ECMAScript does not verify that the number of arguments passed to a function is equal to the number of arguments defined by the function. A developer-defined function can take any number of arguments (up to 255, according to Netscape documentation) without throwing any errors. Any missing arguments are passed to the function as undefined, and extra functions are ignored.
Analog function overloading
To simulate function overloading, use the arguments object to determine the number of arguments passed to the function:

function doAdd() {
  if(arguments.length == 1) {
    alert(arguments[0] + 5);
  } else if(arguments.length == 2) {
    alert(arguments[0] + arguments[1]);
  }
}

doAdd(10);	//output "15"
doAdd(40, 20);	//output "60"

When there is only one argument, the doAdd() function increments the argument by 5. If there are two arguments, the two arguments are added and their sum is returned. So, doAdd(10) outputs “15”, while doAdd(40, 20) outputs “60”.
It’s not as good as overloading, but it’s good enough to get around this limitation of ECMAScript.
Function overview Function object

JS to find the last character of the string and remove it

The first uses the replace method of the string

var str = "hello-world-"
        // \S non-blank character $ ending {1} Match a
        str = str.replace(/\S{1}$/, '');
        console.log(str);

The second way is to use string interception and there are three APIs for string interception and I’m only going to talk about two of them

var str = "hello-world-"
        
 console.log(str.slice(0, -1));

console.log(str.substring(0, str.length - 1));

The final output is hello-world
Watch me keep my front-end knowledge updated

Difference between innerHTML and innerText

The innerText attribute

Set or return the text content as plain text for the specified node and all its children						    						

InnerHTML attribute
Gets and sets the plain text or HTML content in the element
InnerHTML properties are different:

Allows you to use HTML formatted text and does not automatically encode and decode the text.

Vue refreshes the current page (no flash screen will appear)

Vue refreshes the current page (no flash)
No splash screen appears when vUE refreshes the current page

parent-child component values can also be passed after the parent component completes all operations without having to go to the child component </h6 b> 1. Add the v-if attribute

to app.vue

<router-view v-if="isRouterAlive"></router-view>
2. Add isRouterAlive in the data, of course, this property name can be defined by itself, the default value is true
data () {
      return {
        isRouterAlive: true
      }
  }
3. Methods add a refresh method
methods: {
  reload () {
    this.isRouterAlive = false
    this.$nextTick(function() {
       this.isRouterAlive = true
    })
  }
}

4. Finally, we need to provide this function (the same as data) </h6 b>

provide () {
  return {
    reload: this.reload
  }
}

So, that’s all set up on app.vue,
and then when we need to refresh, we just add this function to the page that we need

5. First inject this function
inject: ['reload'] (same to data)
6. Then refer to it where you need this function
refresh () {
this.reload()
}

This will refresh the page without the white screen