JavaScript Basics Quick Start Part 2

 JavaScript Advanced


Arrays and Operation Methods

        An array is a collection of data. In JavaScript, the data in an array can be of different types;

How to define an array

        1. Object instance creation new Array 2. Direct quantity creation

// 对象实例创建
var arr = new Array(1,2,3)

// 直接量创建
var arr = [1,2,3]

Methods for manipulating data in an array

1. Get the length of the array: array name.length 

var arr = [1,2,3,4]        // 长度为4
console.log(arr.length)    // 输出:4

2. Use the subscript to get a value in the array: array name [subscript] (note: the subscript starts from 0 instead of 1)

var arr = [1,2,3,4]  // 下标 0 - 1 ,1 - 2 ,2 -3 ,3 - 4

console.log(arr[0])  // 输出:1
console.log(arr[1])  // 输出:2

// 超出下标
console.log(arr[4])  // 输出:undefined

3. Use the join() method to split, and combine the array members into strings through a splitter

<script type="text/javascript">
    var arr = [1,2,3,4]
    var result = arr.join('-')
    console.log(result) // 输出: 1-2-3-4
</script>

4. push() and pop() add or delete members from the end of the array

var arr = [1,2,3,4]
arr.push(5)        // 在arr数组的后面添加一个数组成员5
console.log(arr)   // 输出:[1,2,3,4,5]

arr.pop()          // 删除arr数组的最后一个数组成员
console.log(arr)   // 输出:[1,2,3,4]

5. reverse() reverses the array

var arr = [1,2,3,4]

arr.reverse()      // 将数组倒过来
console.log(arr)   // [4,3,2,1]

6. indexOf() Returns the index value of the first occurrence of an element in the array

var arr = [1,2,3,4]
alert(arr.indexOf(1))    // 0

7. splice() adds and deletes members in the array

var arr = [1,2,3,4]
arr.splice(2,1,5,6)     // 从下标索引为2开始,删除1个元素,在此处添加5,6两个元素
console.log(arr)        // 1,2,5,6,4
// 只删
arr.splice(1,1)    
console.log(arr)        // 1,5,6,4
// 只增
arr.splice(1,0,2) 
console.log(arr)        // 1,2,5,6,4


Multidimensional Arrays

        Multidimensional arrays are arrays whose members are also arrays of arrays.

var arr = [[1,2,3],[4,5,6]]

// 访问
arr[0] —— [1,2,3] 
arr[1] —— [4,5,6]

arr[0][0] ——  1
arr[0][1] ——  2

arr[1][0] ——  4
arr[1][1] ——  5

        To operate the data in the array in batches, you need to use loop statements.


loop statement

        Perform regular repetitive operations in the program.

for loop -  everyone is already very familiar with this

for(var i = 0 ; i < 10 ; i++){ ... }

ES5 deduplication - for + indexOf + push

var arr = [1,2,3,2,1,4,5,5,4,6]

var newarr = []   // 待接收
for(var i = 0; i < arr.length; i++){
    // indexOf() 会返回第一个出现的下标,那么进行保存到newarr
    if(arr.indexOf(arr[i]) == i){
        // push() 添加到newarr数组
        newarr.push(arr[i]) 
    }
}
console.log(newarr)


Dynamic display of array data

        Display the data in the array on the foreground page.

         This effect can be achieved directly using html and css, so now we need to save these data in an array, and render the data to the front page through javascript operations.

<!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>
</head>
<body>
    <!-- 静态 -->
    <!-- <div id="ct"> 
        <p id="hot-song">热门歌曲</p>
        <ul>
            <li><span class="stitle">程响 —— 人间烟火</span></li>
            <li><span class="stitle">Lil笑笑 —— 山茶树不懂白玫瑰</span></li>
            <li><span class="stitle">赵予希 —— 落日星空</span></li>
            <li><span class="stitle">指尖笑 —— 惊鸿醉</span></li>
        </ul>
    </div> -->
    
    <div id="ct"> 
        <p id="hot-song">热门歌曲</p>
        <ul id="songlists">
        </ul>
    </div>

    <script type="text/javascript">
        // 模拟数据
        var songLists = ['程响 —— 人间烟火','Lil笑笑 —— 山茶树不懂白玫瑰','赵予希 —— 落日星空','指尖笑 —— 惊鸿醉']
        // 进入页面后加载
        window.onload = function(){
            var list = document.getElementById('songlists');
            var sp = document.getElementsByTagName('span')
            var temp = ''

            for(var i = 0 ; i < songLists.length ; i++){
                temp += '<li><span class="stitle">' + songLists[i] + '</span></li>'
            }

            list.innerHTML = temp
        }
    </script>
</body>
</html>
<style>
*{
    padding: 0;
    margin: 0 auto;
}
ul,li{
    list-style: none;
}
p{
    width: 280px;   
    height: 30px;
    line-height: 30px;
    background-image: linear-gradient(to right, rgb(52, 52, 197,0.8) , skyblue);
    padding: 0 10px;
    font-weight: 700;
    color: #fff;
}
li{
    width: 298px;
    height: 30px;
    line-height: 30px;
    border-bottom: 1px solid skyblue;
    border-left: 1px solid skyblue;
    border-right: 1px solid skyblue;
}
.stitle{
    padding: 0 10px;
}
</style>

String handling methods

1. Merge operation of strings: + 

var num1 = 1;
var num2 = '1';
var num3 = 2;
var str = 'hello' 

console.log( num1 + num2 );  // 输出:11 (拼接,类型不同)
console.log( num1 + num3 );  // 输出:3   
console.log( num1 + str );   // 输出:1hello

2. parseInt() converts a numeric string to an integer

var num1 = 12
var num2 = 12
var num3 = '12'
var num4 = 12.20

console.log(...
    num1 + num2             // 输出:24
    num1 + num3             // 输出:1212
    num1 + parseInt(num3)   // 输出:24
    parseInt(num3) + parseInt(num4)     // 输出:24

3. parseFloat() converts numeric strings to decimals

var num1 = '12.21'
console.log(parseFloat(num1))    // 输出:12.21

4. split() splits the string into an array of strings

var date = '2050-12-20'
var arr = date.split('-')
console.log(arr)    // 输出:[2050, 12, 20]

5. indexOf() Find out whether a certain character is contained (returns a Boolean value)

var str = 'abcd'
// 检测str是否有a
var result = str.indexOf('a')
console.log(result)    // 输出:true

// indexOf去重
var arrs = [1,2,2,4,6,6,7,8,3,1,2]
function removeVal(arr) {
    var newarr = []
    for(var i = 0 ; i < arr.length ; i++ ){
        // indexOf - -1则无
        if(newarr.indexOf(arr[i]) === -1){
            newarr.push(arr[i])
        }
    }
    return newarr
}
var rs = removeVal(arrs)
console.log(rs);    // 输入:[1, 2, 4, 6, 7, 8, 3]

6. substring() intercepts a string

  substring(start,end) —— intercept the subscript starting with start to the subscript ending with end

  substring(start) —— intercept the part after the subscript starts with start

var a = 'http://www.baidu.com/'
//  截取域名部分
var rs = a.substring(7,20)  // 截取开始下标为7到结束下标为20的部分
console.log(rs)     // 输出:www.baidu.com

var b = 'http://www.baidu.com/'
var res = a.substring(7)  // 截取开始下标为7到结束下标为20的部分
console.log(res)    // 输出:www.baidu.com/


variable scope

        That is, the scope of variables. Variables in JavaScript are divided into global  variables and local variables ;

Global variables:

        Variables defined outside the function are used by the entire page and can be accessed inside and outside the function;

local variable:

       A variable defined within a function can only be accessed within the function in which the variable is defined, and cannot be accessed externally;

<script>
    // 定义全局变量
    var a = 1;
    function sum() {
        // 定义局部变量 
        var b = 2;
        // sum() 可以访问函数外部的a变量
        console.log(a+b)
    }
    sum()        // 3
    alert(b)     // 报错,b访问不到
</script>

closed function

        Another way of writing anonymous functions in JavaScript is to create a function that is executed at the beginning without naming, generally defined functions and execution functions:

Functions defined and executed in general

function say() {
   alert('Hello')
}
say()

closed function

(function(){
    alert('Hello')
})()


(function(){
    function say() {
        alert('Hello')
    }
    say()
})()


------ 高级写法 ------

;有时在做代码压缩的时候避免前面函数没有添加;导致挨在一起会出错

;!function(){
    function say() {
        alert('Hello')
    }
    say()
}();

;~function(){
    function say() {
        alert('Hello')
    }
    say()
}();

timer

The role of the timer: 1. Call the function 2. Make animation

Types of timers: 1. A timer that executes only once 2. A timer that executes repeatedly

1. Call the function

setTimeOut        只执行一次的定时器
clearTimeOut      关闭只执行一次的定时器

setInterval       反复执行的定时器
clearInterval     关闭反复执行的定时器
// 1000毫秒 = 1秒

var timer1 = setTimeOut(say,2000)    // 在2000毫秒后触发say()
var timer2 = setInterval(say,2000)   // 每隔2000毫秒触发say()

/*
    clearTimeOut(timer1);
    claerInterval(timer2);
*/

function say(){
    alert('Hello')
}

----------------------------------

setTimeOut(function say(){
    alert('Hello')
},2000)

2. Make an animation

one-way movement

[Xiaobai’s analysis: Set properties by positioning, change the position of the box by changing the left value, and at the same time need to use the setInterval timer to repeatedly increase the px value of the left, and to make it slide naturally need to set an appropriate execution time] 

<!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>
        *{
            padding: 0;
            margin: 0;
        }
        #box{
            width: 200px;
            height: 200px;
            background: purple;
            position: fixed;
            top: 0;
            left: 0;
        }
    </style>
</head>
<body>
    <div id="box"></div>

    <script>    
        var obox = document.getElementById('box')
        
        setInterval(movebox,30)
        
        var isLeft = 0
        function movebox() {
            isLeft += 3
            obox.style.left = isLeft + 'px';
        }
    </script>
</body>
</html>

move left and right

        Using one-way will always increase the left to slide to the right. Of course, you can use the conditional statement to judge which px value is reached and turn off the timer. Use this to complete the effect of moving the box back and forth.

 Modify the javascript code of the script tag in the above code:

<script>    
    var obox = document.getElementById('box')
    
    setInterval(movebox,30)

    var isLeft = 0
    var speed = 3

    function movebox() {
        isLeft += speed
        obox.style.left = isLeft + 'px';

        if( isLeft > 600 ){
            speed = -3
        }else if( isLeft < 0){
            speed = 3
        }
    }
</script>

Principle of seamless scrolling

        Understand and use seamless scrolling to know the principle of swiper rotation;

        Let's first use a few pictures to explain the principle of seamless scrolling clearly, and then complete the following case effect;

        How does it work? When the first picture on the left goes to the left and is covered, it needs to be displayed in the most vacant position on the right, and vice versa. But what is the current situation? There are 5 pictures, if you go left or right, only the background will appear and there will be no picture completion; as follows:

         Let's talk about the principle of seamless scrolling, that is, the idea to solve this problem:

        Through the above illustration, you can know what the principle of seamless scrolling is, so let’s complete this case. Here’s the idea of ​​completing this case:

[ Xiaobai’s analysis idea : first, complete the html and css, complete the exercise independently, first use javascript to copy it, not html copy, and then use a setInterval timer to realize the overall movement to the left, you can Referring to the previous one-way and left-right movement, a judgment needs to be made in the function of the timer. When the first copy moves to the right, there will be a blank space on the left, so it is necessary to judge this timing at this time, and then cut it to the copied second copy. Scroll at the beginning of the second copy, and when the second copy goes to the left, there will be a blank at the end. At this time, you need to judge and then switch it back to the beginning of the first copy. Then there are the left button and the right button to control where to go. At this time, the left value of the control positioning is to set the positive and negative values ​​from left to right. Finally, there is another one that stops scrolling when the mouse moves into the box, and moves out. Continue to scroll and go through this way of thinking. If you still don’t know how to do it, you can watch and type it first and then do it yourself. The main thing is to know its principle first, come on! ]

 <style> placed after

<!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>
</head>
<body>
    <div class="btns">
        <div class="left" id="lbtn">&lt;</div>
        <div class="right" id="rbtn">&gt;</div>
    </div>
    <div class="ct" id="slide">
        <ul id="lists">
            <li><img src="https://cdn.cnbj1.fds.api.mi-img.com/nr-pub/202212232348_fcf409105124ab6d9806a51cffcafff1.jpg" /></li>
            <li><img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/710e5107cc2d5e8d0cefa74ee60982ee.jpg" /></li>
            <li><img src="https://cdn.cnbj1.fds.api.mi-img.com/nr-pub/202212232345_c4f8f33857c3e9c7dc3816e14174f3ec.jpg" /></li>
            <li><img src="https://cdn.cnbj1.fds.api.mi-img.com/nr-pub/202207041721_b9b5e0d1404a1b337e1e9a16d5f695fe.jpg" /></li>
            <li><img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/cdb2caa392a7ac34b39cdac260bf84ca.jpg" /></li>
        </ul>
    </div>

    <script>
        window.onload = function(){
            // 获取元素
            var lists = document.getElementById('lists')
            var lbtn = document.getElementById('lbtn')
            var rbtn = document.getElementById('rbtn')

            // 复制一份
            // lists.innerHTML = lists.innerHTML + lists.innerHTML;
            lists.innerHTML += lists.innerHTML

            var isLeft = 0;
            var speed = 3;
            
            // 定时器制动画
            // var timer = setInterval(moveImg,30);

            // 鼠标事件
            // 移入停止动画
            lists.onmouseover = function(){
                clearInterval(timer)
            }
            
            // 移出停止动画
            lists.onmouseout = function(){
                timer = setInterval(moveImg,30);
            }

            // 按钮
            // 左边
            lbtn.onclick = function(){
                speed = -3
            }
            // 右边
            rbtn.onclick = function(){
                speed = 3
            }


            // 定时器function
            function moveImg() {
                var move_l = 0
                isLeft += speed
                lists.style.left = isLeft + 'px'

                // 判断left
                // >0,要去切到第二份复制的开头
                if(isLeft > 0){
                    isLeft = -1000
                }
                // <0,要到切到第一份的开业
                if(isLeft < -1000){
                    isLeft = 0
                }
            }
        }
    </script>
</body>
</html>
    <style>
        *{
            margin: 0;
            padding:0;
        }
        .ct{
            position: relative;
            margin: 10px auto 0;
            width: 1000px;
            height: 200px;
            /* background: red; */
            background-image: linear-gradient(to right,#BAA2F3,#2CBFFE);
            overflow: hidden;
        }
        ul,li{
            list-style: none;
        }
        ul{
            position: absolute;
            left: 0;
            top: 0;
            width: 2000px;
            height: 200px;
        }   
        li{
            float: left;
            margin: 10px 0px 10px 10px; 
            width:188px;
            height: 180px;
            /* background: purple; */
        }
        /* 按钮 */
        .btns{
            width:1000px;
            height: 30px;
            margin: 50px auto 0;
            position: relative;
            /* background: #000; */
        }
        .left,.right{
            width: 40px;
            height: 200px;       
            background: rgb(199, 199, 199,0.3);
            position: absolute;
            left: -50px;
            top: 40px;
            text-align: center;
            line-height: 200px;
            font-weight: bold;
        }
        .right{
            left: 1010px;
        }
        li img{
           width: 100%; 
           height: 180px;
        }
    </style>

JavaScript object

        An object in JavaScript can be understood as a collection of key-value pairs. The key is the name of each value. The value can be a basic quantity, or a function or an object.

Two ways to create JavaScript objects:

1. Instantiate an object through the top-level Object class, and then add properties and methods to the object         

var person = new Object();

// 添加属性
person.name = 'lhxz'
person.age = 18

// 添加方法
person.sayHi = function(){
    alert('Hi!')
}

// 调用属性和方法
alert("I am " + person.name + ", I am " + preson.age)   // I am lhxz, I am 18
person.sayHi()    // Hi

2. Create objects using literals

// var person = {} 空对象

var person = {
    name: 'lhxz',
    age: 18,
    sayHi:function(){
        alert('Hi');
    }
}

// 调用属性和方法
alert(person.age)    // 18
person.sayHi()       // Hi

JSON

        JSON is the acronym for JavaScript Object Notation, which means javascript object representation. The json mentioned here refers to a data format object similar to javascript objects. Currently, this format data is more popular and gradually replaces the traditional xml data format. .

        JSON data objects are similar to objects in Javascript, but there are no functions and methods in the values ​​corresponding to their keys. Values ​​can be ordinary variables, undefined is not supported, and values ​​can also be arrays or json objects.

        Different from the writing method of JavaScript objects, the attribute names and string values ​​of json objects need to be enclosed in double quotes. Using single quotes or not quotes will cause errors in reading data.

Data in json format :

{
    "name" : "lhxz",
    "age" : 18
}

Another data format of json is an array, which is the same as the array literal in javascript:

[ "lhxz" , 18 , "syan" ]

More complex data structures:

{
    "name" : "syan",
    "age" : 18,
    "hobby" : [ "reading" , "writer" ]
    "school" : {
        "name" : "dongneixuexiao"
    }
}

Guess you like

Origin blog.csdn.net/weixin_52203618/article/details/129727856