Introduction to string, array, date and other objects in js and common string methods and array methods

object

Everything in JavaScript is an object: strings, numbers, arrays, dates, and so on.
In JavaScript, an object is data that has properties and methods.

Property is a value associated with an object.
Methods are actions that can be performed on objects Keywords ()
For example: cars are objects in real life.

Car properties:
car.name=Fiat name
car.model=500
car.weight=850kg
car.color=white color

Method of vehicle:
car. Start
car. Drive
car. Brake

Object object

create object

var Object name=new Object();

Set object properties

Object name.Attribute name=value;

Set object method

Object name.Method name=function(){ }  

Call object properties

 Object name.Attribute name

Call object method

 Object name.Method name()

String object

Create a String object

​ var strOb = new String("abcefg");
​ var strOb = String("abcefg");
​ var strOb = "abcefg";

attribute

Length (string length)

method

  1. Substring position
    indexOf(string,[index]) / / returns the first occurrence of the substring abc in the string (calculated from 0). If it does not exist, it returns - 1

    String: the content of the searched string, which is required

    index: start to find the location, optional

    Return value: the return value is the position (subscript) of the found substring. By default, the first found content is returned; If the searched content does not exist, - 1 is returned

  2. lastIndexOf(string,[index]) / / returns the last occurrence of the substring abc in the string

    String: substring, the content of the searched string, required

    index: start to find the location, optional

    Return value: the return value is the position (subscript) of the found substring. By default, the first found content is returned; If the searched content does not exist, - 1 is returned

// eg: find afgdtywgbfnjekagrn how many times in the string g 
var str = new String('afgdtywgbfnjekagrn');
var index = str.indexOf('g'); // 2
// Statistical times
var num = 0;
while(index !== -1){ // lookup
    num++;
    index = str.indexOf('g',index + 1);
}
console.log('g A total of'+num+'second');
// Wrapper function - find the number of occurrences of a substring
function counts(str,cStr){
    var index = str.indexOf(cStr);
    var num = 0; // Number of occurrences

    while(index != -1){
        num++; // Times + 1 for each occurrence
        index = str.indexOf(cStr,index+1);
    }
    return num;
}
var n = counts('38qhdahwdqjk24hjoiyowuierfy8','o');
alert('O A total of'+n+'second');
  1. slice(start,end) gets a part of a string

    Interception is included before and not included after

    Start indicates the start position, starting from 0 to positive infinity

    End indicates the end position, which can be positive or negative

// Basic use
var str = 'hello wolrd';
console.log(str.slice(3,5));
console.log(str.slice(3,-1));

// Case: use slice and timer to realize the output of content
var str = 'My name is Zhang San. I'm thirteen years old';
var oBox = document.querySelector('#box');
var i = 0;
function show(){
    if(i<str.length){
        oBox.innerHTML += str.slice(i,++i); // Method 1
        oBox.innerHTML += str.charAt(i++); // Method 2
        setTimeout(show,100);
    }
}
show();
  1. intercept
    Substr (start position, [interception length]) / / if the interception is not written, it means that the end of the string is intercepted

    Starting position: can be customized, starting from 0

    Intercept length: it can be a number or not written; If the length is not written, it indicates that it is intercepted to the end of the string

    Return value: the intercepted string

Substring (start position, [end position]) / / does not include the right boundary character of the interception result

Start position: it is a subscript value and cannot be negative

End position: it is a subscript value and cannot be negative (excluding the right boundary character of the interception result)

// Demand: judge what kind of picture it is; The format of the photo must be png/jpg txt
// Get the suffix of the file name - the subscript at the beginning of the suffix - lastIndexOf / substr
function getSuffix(){
   var file = document.getElementById('files');
   var pic = file.value;// Path of picture
   // var pic = '.././images/banner/one.txt'; 
   var suffix = pic.substr(pic.lastIndexOf('.')+1);
   if(suffix=='png'||suffix=='pneg'||suffix=='jpg'||suffix=='jpeg'){
       alert('The picture format is correct');
   }else{
       alert('Incorrect format!');
    }
}
<!-- Upload the file and judge whether the file format is correct -->
<input type="file" id='file'>
<button id='btn'>Submit</button>
<script>
    var oBtn = document.querySelector('#btn');
    var oFile = document.querySelector('#file');
    oBtn.onclick = function(){
        var res = getStr(oFile.value);
        if(res){
            alert('Upload successful')
        }else{
            alert('The picture format is incorrect')
        }
    }
</script>
  1. replace
    replace('substring 1 ',' substring 2 ') / / replace substring 1 with substring 2
var str='My name is apple. So I like to eat apple very much!';
// 1. Ordinary replacement
alert(str.replace('apple','banana'));
alert(str.replace(/apple/g,'banana'));

// 2. Replace all numbers with spaces
var str2 = 'Zhang San 1 Li Si 2 Wang Wu 3 Ma Liu';
alert(str2.replace(/[0-9]/g,' '));

// 3. Replace all lowercase letters with spaces
var str2 = 'Zhang San w Li Si f Wang Wu n Ma Liu';
var newStr2 = str2.replace(/[a-zA-Z]/g,' '); 
console.log(newStr2);

//  4. Replace all letters with spaces [case insensitive]
var str2 = 'Zhang San w Li Si F Wang Wu n Ma Liu';
// var newStr2 = str2.replace(/[a-zA-Z]/g,' '); 
var newStr2 = str2.replace(/[a-z]/gi,' '); 
console.log(newStr2);
  1. Gets the character at the specified position

    charAt(n) defaults to the first character

    n refers to the subscript, the range is 0-positive infinity, and negative values cannot be used

  2. Gets the ASCII encoding str.charCodeAt() of the specified character

var str1 = 'helloworld';
var getStr1 = str1.charCodeAt(2);
console.log(getStr1);
  1. Convert case
    toLowerCase()
    toUpperCase()

    <!-- Login verification code effect -->
    <input type="text" id='inp'><span>tR4wC</span><br/>
    <button id='btn'>Button</button>
    <script>
        // Rules of analog verification code
        // 1. Find the button
        var oBtn = document.querySelector('#btn');
        // 3. Get the contents of input
        var oInp = document.querySelector('#inp');
        // 4. Get the contents in span
        var oSpan = document.querySelector('span');
        // 2. Add click event
        oBtn.onclick = function(){
            // 5. Capitalize the contents of input
            var inp = oInp.value.toUpperCase();
            // 6. Capitalize the contents of span
            var yanzheng = oSpan.innerText.toUpperCase();
            if(inp == yanzheng){
                console.log('Verification successful');
            }else{
                console.log('Validation failed');
            }
        }
    </script>
    
  2. Split string into arrays
    Split (delimiter, [return maximum length of array])

    Separator: it is a string type or regular expression

    Return value: array

  3. Show string effect
    bold() bold () italics() Italic strike() delete fontcolor('#f00') fontsize(1-7) sup() sub()

var oFont = document.getElementById('font');
var val = oFont.innerText;
oFont.innerHTML = val.big().fontcolor('red').strike().fontsize(18);
// oFont.innerHTML = val.sub()
console.log(val.sub());
  1. Set as hyperlink

    link(url)

var oBox = document.querySelector('#box');
oBox.innerHTML = str.strike().fontsize(7).fontcolor('red').italics().link('http://www.baidu.com');
<!-- Text search effect -->
<div class="box">
        At the end of the galaxy, I'm afraid it's carrying goods!<br/>
        Recently, Meng Yutong, the successor of "Iron Lady" Dong Mingzhu, came out of the circle and became popular a few days later
</div>
<input type="text" name="" id="inp">
<button id='btn'>lookup</button>

<script>
    // 1. Click the Find button
    var oBtn = document.querySelector('#btn');
    var oInp = document.querySelector('#inp');
    var oBox = document.querySelector('.box');
    oBtn.onclick = function(){
        // 2. Get the value in input
        var val = oInp.value;
        console.log(val.fontcolor('red'));
        // 3. Add a red text style to the value in input
        var newVal = val.fontcolor('red').bold();
        // 4. Directly use replace to replace the changed text
        // var reg = /[num]/g;
        var reg=new RegExp(val,'g');
        var newInner = oBox.innerHTML.replace(reg,newVal);
        // console.log(newInner);
        oBox.innerHTML =  newInner;
    }
</script>
// The function is imperfect and needs to be modified

Date object

Creating Date Objects

var dateObj=new Date();

method

1. Convert date to string
  toLocaleString()  
  toLocaleDateString() 
  toLocaleTimeString()
  1. Get year, month, day, hour, minute and second

    getYear() / / two digit year (before 2000) or three digit year [1900]
    getFullYear() / / four digit year
    getMonth() / / month + 1
    getDate() / / day
    getHours() / / hours
    getMinutes() / / minutes
    getSeconds() / / seconds
    Gettime() / / milliseconds since January 1, 1970

  2. timer

    Setinterval (function body, time (MS), parameter (parameter passed to function))

    // Time jitter case
    function getT(){
            // Get time
            var d = new Date();
            var year = d.getFullYear(); 
            var month = d.getMonth()+1;
            var day = d.getDate();
            var h = d.getHours();
            var m = d.getMinutes();
            var s = d.getSeconds();
            var ms = d.getMilliseconds();
            var oTime = document.getElementById('times');
            oTime.innerHTML = year+'-'+month+'-'+day+' '+h+':'+m+':'+s+' '+ms;
    }
    function stop(){
            // Clear a timer clearinterval (the name of the timer);
            clearInterval(myTime);
    }
    
  3. How to calculate the time difference

    Use timestamp to calculate time difference

    2021-9-5 10:30:20 -> 1630809020000

    2020-8-9 12:30:45 -> 1596947445000

    How many years, days, hours, minutes, seconds

    Timestamp reference time: 1970 / 1 / 1 0:0:0 (Greenwich mean time)

    1970 / 1 / 1 8:0:0 (Beijing time)

    Timestamp: d.getTime(); The unit is milliseconds

        var aTime = new Date('2021-9-5 10:30:20'); // Specified time
        var bTime = new Date('2021-8-5 8:20:10');  // 
        var cha = aTime.getTime() - bTime.getTime();
        if(cha<=0){
            console.log('Wrong time input!');
        }else{
            var miao = cha / 1000; // Units of seconds
            var s = miao % 60; // second
    
            var fen = parseInt(miao / 60); // Units of minutes
            var m = fen%60;// minute
    
            var hour = parseInt(fen / 60); // Unit of hour
            var h = hour % 24; // hour
    
            var day = parseInt(hour / 24); // day
            var d = day % 365;
    
            var y = parseInt(day/365); // year
    
            console.log('The difference between the two times:'+y+'In,'+d+'God,'+h+'Hours,'+m+'minute,'+s+'second'); 
        }
    

    Case: Suning Tesco shows rush buying activities

  4. Set time

    1. Directly set year, month, day, hour, minute and second

    new Date() gets the current time

    New date (string / timestamp / value); Gets the specified time

    String: "2021-2-3 12:23:34"

    Timestamp: 1617589820000

    Value: 2012,5,6,12,30,00

    ​ 2. Simple setting time

    set... [not used much]

    ​ setMonth();

    ​ setDate();

    ​ setFullYear();

    Case: someone has been fishing for three days and screening for two days since August 8, 2008. Q: should I fish today or screen tomorrow? What about today next year?

Array object

Create array object

Var arrob = new array (value,...)
Var arrob = array (value,...)
var arrOb = [value,...]
var arrOb=new Array(n);
arrOb[0] = value 1;
arrOb[1] = value 2;
...

attribute

length / / number of elements in the array

method

  1. Convert to string
    toString() / / convert the array into a string and connect it with commas
    join('connector ') / / connect array elements into strings

    var arr = ['Yunnan','jiuzhaigou','Lhasa','Xishuangbanna','Sanya','Shaolin Temple'];
    console.log(arr.toString());
    console.log(arr.join('')); // The content in the linked array has no connection symbol
    console.log(arr.join('*'));
    var str = arr.join('-');
    console.log(str.split('-'));
    
    // Exercise: write a function to capitalize the first letter of each word in the incoming string, and enter capitalize('the quick brown fox '); Return to The Quick Brown Fox
    function capitalize(str){
       var arrStr = str.toLowerCase().split(' ');
       for(var i=0;i<arrStr.length;i++){
            arrStr[i] = arrStr[i].replace(arrStr[i][0],arrStr[i][0].toUpperCase());
       }   
       // console.log(arrStr); //  array
       return arrStr.join(' ');
    }
    var getStr = capitalize('heLLo woRld xiaoMing');
    console.log(getStr);
    
  2. Connect multiple arrays and return a new array
    Concat (string / array / number) / / connect multiple arrays and return a new array

  3. Append elements and return the length of the new array
    unshift(value,...) / / append header

    push(value,...) / / append at the end

  4. Delete the element and return it
    shift() / / delete the first element

    pop() / / delete the last element

  5. Delete an element or delete and insert a new element
    Splice (start position, length, new content 1, new content 2... New content n) / / returns an array including deleted elements

  6. Sort array elements in ascending order
    Sort (callback function)

  7. Invert elements in an array
    reverse()

Case: a random number of 1-100 is returned randomly, and the value cannot be repeated

var arr=[];
for(var i=0;i<10;i++){
	var num=Math.floor(Math.random()*100);
	arr.push(num);
}
// Case: it is required to remove 0 items from the array
var arr = [4, 0, 7, 9, 0, 0, 2, 6, 0, 3, 1, 0];

Deep copy shallow copy

reflection:

var arr=[1,2,3,4];
arr1 = arr;
arr[1] = 'hello';
console.log(arr);
console.log(arr1);

reference material:

https://www.cnblogs.com/echolun/p/7889848.html

Math object

Math object is a built-in object of Javascript and can be used directly without instantiation

attribute

Math.PI

method

​ Math.round(number) / / round to an integer
​ Math.ceil(number) / / round up
​ Math.floor(number) / / round down
​ Math.random() / / randomly returns a number between 0.0 and 1.0
​ Math.max(x,y) / / find the maximum value
​ Math.min(x,y) / / find the minimum value
​ Math.pow(x,y) / / find xy

Gets a random number in the specified range

Math.floor(Math.random()*(max-min+1))+min

Global object

The Global object is the most special object in ECMAscript because it doesn't exist at all. It doesn't exist because there are no independent functions in ECMAscript. All functions must be methods of an object.

For example, isnan(), isfinish(), parseint() and parseFloat() are all methods of Global objects

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-GPr5lYyv-1645865632488)(... / images/image-20210829161735537.png)]

  1. Encoding function escape()
  2. Decoding function (unescaoe)
  3. Evaluation function eval()
  4. Check whether a value is a number isNaN

Assignment: from simple to difficult

Ask more questions

For the knowledge points you haven't learned, note them in advance

More questions and problem solving ideas

Knowledge points

Add code comments

Keywords: Javascript Front-end html

Added by Xiphoid8 on Sat, 26 Feb 2022 11:02:00 +0200