day6 js基礎

1、變量的作用域


<script type="text/javascript">
    //函數(shù)聲明語法:
    /*
     function 函數(shù)名(參數(shù)列表){
        函數(shù)體
     }
     
     函數(shù)變量 = function (參數(shù)列表){
        函數(shù)體
     }
     */
    
    
    //1.全局變量: 
    /*
     * a.聲明在函數(shù)外部的變量(從聲明開始到文件結(jié)束都可以使用)
     * b.直接聲明在函數(shù)內(nèi)的變量(不加var)
     * 注意:后面的其他的script標簽中也可以使用
     */
    a100 = 10
    var a200 = 100
    
    
    //2.局部變量
    /*
     * 通過var關(guān)鍵字聲明在函數(shù)里面的變量是局部變量(聲明開始到函數(shù)結(jié)束可以使用)
     */
    function func2(){
        //b100是全局變量
        b100 = 20
        //b200是局部變量
        var b200 = 200
        console.log(b200)
    }
    func2()
    
    console.log(b100)
    
    
    function func1(){
        console.log(a100)
        console.log(a200)
        console.log(b100)
    }
    func1()
    
    b = 1
    while(b < 5){
        console.log(a100)
        console.log(a200)
        console.log(b100)
        b++
    }
    
    
    
    
</script>


<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    </body>
</html>

<script type="text/javascript">
    console.log(a100)
    console.log(a200)
    console.log(b100)
</script>

2、字符串

<script type="text/javascript">
    //1.字符串運算
    //a.加法運算: 做字符串拼接操作
    //注意:js中支持字符串和其他數(shù)據(jù)相加
    str1 = 'abc'
    str2 = 'hello'
    console.log(str1+str2)   //abchello
    console.log(str1+100)    //abc100
    console.log(str1+[1,2,3])  //abc1,2,3  
    
    //b.比較運算: >, <, >=, <=,==, ===, !=, !== 
    //1)比較相等
    console.log('abc'=='abc')   //true
    console.log('abc'=='bac')   //false
    console.log(100=='100')   //true
    console.log(100==='100')  //false
    //2)比較大小: 和python字符串比較大小的方式一樣
    console.log('abc' > 'bd')  //false
    console.log('z' > 'shjsjhsjasss')   //true  
    
    //c.字符串長度
    //字符串.length
    console.log(str2.length)
    
    //2.相關(guān)方法
    //創(chuàng)建字符串對象
    str3 = new String('abc')
    console.log(str3)
    
    //1).big方法
    //產(chǎn)生一個big標簽,并且標簽中的內(nèi)容就是字符串的值
    newStr = str3.big()
    console.log(str3, newStr)  
    
    //2).字符串.charAt(下標)
    //獲取指定下標對應的字符; 相當于: 字符串[下標]
    console.log('hello'.charAt(0))   //h
    console.log('hello'[1])    //e
    
    //3).字符串.charCodeAt(下標)
    //獲取指定下標對應的字符的編碼(js中的字符采用的也是unicode編碼)
    console.log('hello'.charCodeAt(0))   //104
    
    //4)字符串.concat(數(shù)據(jù)1,數(shù)據(jù)2,....)
    //將字符串和多個數(shù)據(jù)依次連接在在一起產(chǎn)生一個新的字符串(相當于+的功能)
    console.log('abc'.concat(123, 'aaa'))   //abc123aaa  
    
    //5)字符串1.endsWith(字符串2)
    //判斷字符串1是否以字符串2結(jié)尾
    console.log('hello'.endsWith('llo'))   //true   
    
    //6)字符串1.indexOf(字符串2)
    //獲取字符串2在字符串1中第一次出現(xiàn)的位置
    console.log('abcbaab'.indexOf('b'))
    
    //7)字符串1.lastIndexOf(字符串2)
    //獲取字符串2在字符串1中最后一次出現(xiàn)的位置
    console.log('abcbaab'.lastIndexOf('b'))  
    
    //8)字符串.match(正則表達式)
    //相當于python中re模塊的match; 匹配成功返回
    //注意:js中正則寫在兩個//之間
    re = /\d{3}/
    result = '237abc'.match(re)
    console.log(result, result[0], result.index)  
    
    //9)字符串.repeat(數(shù)字)
    //指定的字符串重復出現(xiàn)指定次數(shù)產(chǎn)生一個新的字符串(相當于python中的*)
    console.log('abc'.repeat(2))
    
    //10)字符串1.replace(正則表達式,字符串2)
    //將字符串1中第一個面子正則表達式的子串替換成字符串2
    console.log('aaa34bbb992nnn92nkkj8==22jkk'.replace(/\d+/, 'A'))
    
    //11)字符串.slice(開始下標, 結(jié)束下標)
    //從開始下標獲取到結(jié)束下標前為止,步長是1
    //注意: 這兒的下標可以是負數(shù),代表倒數(shù)第幾個
    console.log('hello'.slice(0, 2))    //he
    console.log('hello'.slice(1, -2))   //el
    
    //12)字符串1.split(字符串2)
    //將字符串1按照字符串2進行切割,返回一個數(shù)組
    console.log('hello'.split('e')) 
    

    
</script>


<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    </body>
</html>

3、數(shù)組

<script type="text/javascript">
    //1.基本操作
    //1).加法運算: 兩個數(shù)組相加實質(zhì)是將數(shù)組轉(zhuǎn)換成字符串然后拼接
    console.log([12, 3, 'abc']+[1, 2, 3])  //12,3,abc1,2,3 
    console.log(String([1, 2, 3]))  //1,2,3
    //2).比較運算: 
    //==、===判斷相等是判斷地址是否相等,相等于python中的is
    arr1 = [1, 2]
    arr2 = [1, 2]
    arr3 = arr1
    console.log(arr1===arr1)   //true
    console.log(arr1==arr3)    //true
    console.log(arr1==arr2)    //false
    
    //3).數(shù)組長度: length屬性
    console.log(arr1.length)
    
    //2.元素的增刪改查  
    //1)查: 獲取元素
    //a.獲取單個元素
    //數(shù)組[下標]  - 獲取下標對應的元素
    //注意:負數(shù)的下標沒有意義
    fruits = ['蘋果', '梨', '葡萄', '西瓜', '桃子', '李子']
    console.log(fruits[1])   
    
    //b.切片:
    //數(shù)組.slice(開始下標,結(jié)束下標)   -  返回一個新的數(shù)組
    //注意:結(jié)束下標取不到;下標可以是負數(shù); 開始下標要在結(jié)束下標的前面
    console.log(fruits.slice(0, 3))    //['蘋果', '梨', '葡萄']
    console.log(fruits.slice(3, 0))    //[]
    console.log(fruits.slice(3, -2))   //['西瓜']  
    
    //c.遍歷
    for(index in fruits){
        console.log(fruits[index])
    }  
    
    //2)增:添加元素
    //數(shù)組.push(元素) - 在指定的數(shù)組的最后添加一個元素
    fruits.push('香蕉')
    console.log(fruits)
    
    //3)刪:刪除元素
    //數(shù)組.pop()  - 刪除最后一個元素
    fruits.pop()
    console.log(fruits)    //["蘋果", "梨", "葡萄", "西瓜", "桃子", "李子"]
    
    //數(shù)組.splice(下標,個數(shù))  - 從指定下標開始刪除指定個數(shù)的元素
    fruits.splice(1, 2)    
    console.log(fruits)     // ["蘋果", "西瓜", "桃子", "李子"]  
    
    //4)改: 修改元素
    //數(shù)組[下標] = 新值   - 修改指定下標對應的值
    fruits[0] = '山竹'
    console.log(fruits)
    
    
    //3.相關(guān)方法
    fruits = ['蘋果', '梨', '葡萄', '西瓜', '桃子', '李子']
    //1)數(shù)組.reverse() 
    //倒序
    fruits.reverse()
    console.log(fruits)    //["李子", "桃子", "西瓜", "葡萄", "梨", "蘋果"]  
    
    //2)數(shù)組.sort()
    //元素從小到大排序
    scorts = [23, 90, 89, 87, 76, 90, 65]   //[23, 65, 76, 87, 89, 90, 90]
    scorts.sort()
    console.log(scorts)   //["李子", "桃子", "梨", "蘋果", "葡萄", "西瓜"]
    
    
    //數(shù)組.sort(函數(shù)) - 按指定規(guī)則對數(shù)組中的元素進行排序
    //函數(shù)的要求: 兩個參數(shù)(代表的是數(shù)組中的兩個元素),一個返回值(兩個元素或者兩個元素的屬性的差); 
    students = [
        {'name':'小明', 'score': 60, 'age': 29},
        {'name':'張三', 'score': 89, 'age': 30},
        {'name':'小花', 'score': 81, 'age': 19}
    ]
    
    //按成績從小到大排序
//  function ageCom(item1, item2){
//      return item1['score']-item2['score']
//  }
//  students.sort(ageCom)
//  console.log(students)  
    
    //年齡從大到下排序
    students.sort(function(a,b){
        return b['age'] - a['age']
    })
    console.log(students)  
    
    //3) 數(shù)組.join(字符串)
    //將指定的字符串插入到數(shù)組的每個元素之間產(chǎn)生一個新的字符串
    nums = [10, 34, 89, 1]
    newData = nums.join('aaa')
    console.log(newData)    // 10aaa34aaa89aaa1

    
</script>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    </body>
</html>

4、對象

<script type="text/javascript">
    //1.對象字面量
    //用大括號括起來,里面是多個屬性,屬性名和屬性值之間用冒號連接, 多個屬性之間用逗號隔開
    //注意: 1)對象字面量需要保存  2)屬性名可以加引號也可以不加(沒有區(qū)別)
    obj1 = {
        'name':'余婷',
        'age': 18,
        sex: '女'
    }
    p1 = {
        'name':'小明',
        'age': 20,
        sex: '男'
    }
    console.log(obj1)   
    
    //2.獲取對象屬性對應的值
    //1) 對象[屬性名]
    console.log(obj1['name'], obj1['sex'])
    
    proName = 'age'
    console.log(obj1[proName])
    
    //2) 對象.屬性
    console.log(obj1.name, obj1.sex)  
    
    //3.增/改: 添加/修改屬性
    //1)對象.屬性 = 值
    //2)對象[屬性名] = 值
    //屬性存在是修改
    obj1.name = '小明'
    obj1['name'] = '小花'
    console.log(obj1)
    
    //屬性不存在是添加
    obj1.height = 180
    obj1['weight'] = 70
    console.log(obj1)  
    
    //4.構(gòu)造方法 - 創(chuàng)建對象的方法
    /* 語法:
     * function 類名(參數(shù)列表){
     *      對象屬性
     *      對象方法
     * }
     * 
     * 說明:
     * a.對象屬性: this.屬性名 = 值
     * b.對象方法: this.方法名 = 匿名函數(shù)
     * c.類名: 首字母大寫
     */
    function Person(name='張三', age=18, sex='男'){
        //這兒的this相當于python中的self
        //對象屬性
        this.name = name
        this.age = age
        this.sex = sex
        //對象方法
        this.eat = function(food){
            console.log(this.name+'吃'+food)
        }
        console.log('=====:',this)
    }
    //5.創(chuàng)建對象
    // 對象 = new 構(gòu)造方法()
    //創(chuàng)建對象
    p1 = new Person()
    console.log(p1)
    //獲取對象屬性
    console.log(p1.name, p1.age, p1.sex)
    //調(diào)用對象方法
    p1.eat('包子')
    
    p2 = new Person('小明', 20, '女')
    console.log(p2)
    p2.eat('面條')
    
    
    //注意: js中聲明全局變量實質(zhì)都是添加給window對象的屬性
    p3 = Person()
    p3 = window.Person()
    console.log(p3)
    
//  window.alert('彈框')
    alert('彈框')
    a = 10
    console.log(window.a)
    
    //6.添加類的全局的屬性
    //類名.prototype.屬性名 = 屬性值   -  給指定的類的所有對象添加屬性
    Person.prototype.height = 180
    Person.prototype.run = function(){
        console.log(this.name+'在跑步!')
    }
    p4 = new Person('老駱', 30, '男')
    
    console.log(p4.height, p1.height)
    p4.run()
    p1.run()
    p2.run()
    
    //練習: 給數(shù)組添加方法,來統(tǒng)計數(shù)組中指定元素的個數(shù)
    Array.prototype.ytCount = function(item){
        num = 0
        for(i in this){
            item1 = this[i]
            if(item1 == item){
                num++
            }
        }
        return num
    }
    console.log([1, 2, 4, 3, 5, 2, 1, 2].ytCount(1))
    
    //練習1: 聲明一個創(chuàng)建學生的構(gòu)造方法,有屬性姓名、年齡、成績、學號,
    //要求創(chuàng)建學生對象的時候姓名必須賦值,年齡可以賦值也可以不賦值,成績和學號不能賦值  
    function Student(name, age=0){
        this.name = name
        this.age = age
        this.score = 0
        this.studyId = '001'
    }
    
    stu1 = new Student('小明')
    console.log(stu1)
    
    
    //練習2:給String添加方法, 統(tǒng)計字符串中字母字符的個數(shù)
    str1 = new String('abc')
    console.log(str1)
    String.prototype.letterCount = function(){
        num = 0
        i = 0
        while(i<this.length){
            ch = this[i]
            console.log('++:',ch)
            if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z')){
                console.log('====',ch,'=====')
                num++
            }
            i++
        }
        return num
    }
    console.log('A23adb33'.letterCount())
    
    
    //7.系統(tǒng)的對象和類
    //document對象  
    //window對象
    //Element類型的對象
    //Date類型的對象
    //....
    //創(chuàng)建當前時間對象
    date1 = new Date()
    console.log(date1)
    //年
    year = date1.getFullYear()
    //月 - 從0開始的
    month = date1.getMonth()
    //日
    day = date1.getDate()
    //時
    hours = date1.getHours()
    //分
    min = date1.getMinutes()
    //秒
    seconds = date1.getSeconds()
    //星期
    week = date1.getDay()
    console.log(''.concat(year,'年',month+1,'月',day,'日',' ',hours,':',min,':',seconds))
    console.log('星期', week)

    
</script>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    </body>
</html>

5、DOM操作


<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <p id="p1">我是段落</p>
        
        <a href="" class="c1">我是a標簽</a>
        <h1 class="c1">我是標題1</h1>
        
        <input type="" name="userName" id="userName" value="" />
        
        <div id="div1">
            <p>我是段落2</p>
            <a href="">新浪</a>
            <h2>我是標題2</h2>
        </div>
    </body>
</html>
<script type="text/javascript">
    //1.DOM(文檔對象模型: document object mode)
    //1)document對象: 指的是指向整個網(wǎng)頁內(nèi)容的一個對象
    //2)節(jié)點: Element類型對象,指向的是網(wǎng)頁中的標簽

    //2.獲取節(jié)點
    //1)通過id獲取節(jié)點: getElementById(id值) - 返回節(jié)點對象(實質(zhì)就是指向指定標簽的對象)
    p1Node = document.getElementById('p1')
    console.log(p1Node)
    //innerText是標簽文本內(nèi)容
    p1Node.innerText = 'hello js'  
    
    //2)通過class獲取節(jié)點: getElementsByClassName(class值) - 返回節(jié)點數(shù)組
    c1Nodes = document.getElementsByClassName('c1')
    c1Nodes[0].innerText = '百度一下'
    console.log(c1Nodes)
    //注意: 遍歷的時候不要用for in
    for(i=0;i<c1Nodes.length;i++){
        c1Node = c1Nodes[i]
        //修改樣式中的文字顏色
        c1Node.style.color = 'red'
    }  
    
    //3) 通過標簽名獲取節(jié)點: getElementsByTagName(標簽名)
    h1Nodes = document.getElementsByTagName('h1')
    console.log(h1Nodes)   
    
    //4) 通過name屬性值獲取節(jié)點:getElementsByName(name值) (了解)
    nameNodes = document.getElementsByName('userName')
    console.log(nameNodes)
    
    //5)獲取子節(jié)點
    //節(jié)點對象.children - 獲取指定節(jié)點中所有的子節(jié)點
    div1Node = document.getElementById('div1')
    div1Children = div1Node.children
    console.log(div1Children)  
    
    //獲取第一個子節(jié)點
    //節(jié)點對象.firstElementChild
    firstNode = div1Node.firstElementChild
    console.log(firstNode)
    
    //獲取最后一個子節(jié)點
    //節(jié)點對象.lastElementChild
    lastNode = div1Node.lastElementChild
    console.log(lastNode)
    
    //6)獲取父節(jié)點
    bodyNode = div1Node.parentElement
    console.log(bodyNode)  
    
    //3.創(chuàng)建和添加節(jié)點
    //1)創(chuàng)建節(jié)點
    //document.createElement(標簽名)
    //創(chuàng)建一個img標簽
    imgNode = document.createElement('img')
    imgNode.src = 'img/luffy.jpg'
    
    //2)添加節(jié)點
    //節(jié)點1.appendChild(節(jié)點2)  -  在節(jié)點1的最后添加子標簽節(jié)點2
    bodyNode.appendChild(imgNode)  
    //節(jié)點1.insertBefore(新的節(jié)點, 節(jié)點2)  - 在節(jié)點1中的節(jié)點2的前面添加一個新的節(jié)點
    bodyNode.insertBefore(imgNode, bodyNode.firstElementChild)
    bodyNode.insertBefore(imgNode, c1Nodes[0])
    
    //注意:一個節(jié)點不管添加幾次,只有最后一次添加有效(因為節(jié)點只有一個)
    
    //4.拷貝/復制節(jié)點
    //節(jié)點.cloneNode()
    newImgNode = imgNode.cloneNode()
    newImgNode.src = 'img/aaa.ico'
    div1Node.appendChild(newImgNode)  
    
    //5.刪除節(jié)點
    p1Node = document.getElementById('p1')
    //節(jié)點.remove()  - 刪除指定的節(jié)點
    p1Node.remove()   
    
    //節(jié)點1.removeChild(節(jié)點2) - 刪除節(jié)點1中的節(jié)點2
//  div1Node.removeChild(div1Node.lastElementChild)
//  div1Node.removeChild(div1Node.firstElementChild)
    
    //6.替換節(jié)點
    //節(jié)點1.replaceChild(新節(jié)點, 舊節(jié)點)   -  用新節(jié)點替換節(jié)點1中的舊節(jié)點
    bodyNode.replaceChild(imgNode.cloneNode(), c1Nodes[1])
    

    
    
    
    
    
</script>


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • 第3章 基本概念 3.1 語法 3.2 關(guān)鍵字和保留字 3.3 變量 3.4 數(shù)據(jù)類型 5種簡單數(shù)據(jù)類型:Unde...
    RickCole閱讀 5,524評論 0 21
  • 01.js引入方式和打印方式 02.函數(shù) 03.數(shù)組 04.對象 05.常用對象和函數(shù) 06.js簡單演示 07....
    zhazhaK丶閱讀 354評論 0 1
  • 由于東野圭吾說的“站在人生的岔路口,人究竟應該怎么做?”帶著好奇我看了《解憂雜貨店》這本書。 所有事情都淡淡地描述...
    遇見小吉閱讀 651評論 0 0
  • 喝了幾口酒,在不知名的小巷,晃晃悠悠的行走,路上人擁擠得很,面帶笑容,沒人會發(fā)現(xiàn)你臉上的紅暈。 大概很久之前,做過...
    二十七的七閱讀 392評論 0 0
  • 近日來天氣不好,陰雨綿綿,地上濕漉漉的,什么也不能干,出門出行都要帶把傘。從樓頂往地下張望,五顏六色的雨傘開出了一...
    向晨光微笑閱讀 659評論 0 1

友情鏈接更多精彩內(nèi)容