javascript学习快速入门

JavaScript

基本语法

快速入门

数据类型

123 // 整数123
123.1 //浮点数123.1
1.123e3 //科学计数法
 -99//复数
NaN// not a number
 Infinity //表示无限大
注意点

NaN===NaN,这个与所有的数值都不相等,包括自

只能通过isNaN(NaN)来判断这个数是否是NaN

字符串

abc' "abc"

布尔值

true,false

逻辑运算

&&两个都为真, 结果为真

||一个为真,结果为真

!真即假,假即真

null和undefined

●null 空

●undefined 未定义

数组
  var arr = [1, 2, 3, "xu", null, true]

        console.log(arr);
对象
 var Person = {
            name: "陈平安",
            age: 18,
            height: 1.75,
            arr: [1, 2, 3, 4, 5, 6]
        }
        console.log(Person);
        console.log(Person.height);
严格检查模式'use strict';

前提: IEDA需要设置支持ES6语法

严格检查模式,预防JavaScript 的随意性导致产生的-些问题

必须写在JavaScript的第-行!

局部变量建议都使用let去定义~

数据类型

3.1.字符串

转义字符\
  var a = " \u4e2d";
        console.log(a);
多行字符串编写
  var zifuchaun = `
        
        nihao
        whaor
        niaf
        123
        `
        console.log(zifuchaun);
模板字符串
        let name = "陈平安"
        let msg = `你好呀,${name}`
字符串长度

str.length

console.log(msg.length)
字符串的可变性,不可变
大小写转化
 let student = "student";
 大写
 console.log(student.toUpperCase());
 小写
  console.log(student1.toLowerCase());
indexOf() 获取指定下标

通过元素获得下标索引

student1.*indexOf*("T") 
substring()

[)

 console.log(student1.substring(1));从第一个字符申截取到最后一个字符申

 console.log(student1.substring(1, 3));//包含第一个不包含第三个

3.2数组

Array可以包含任何的数据类型

 var arr = [1, 2, 3, 4, 5]
        console.log(arr);
           console.log(arr[]);
        console.log(arr.length + 4);
1.获取长度arr.length
2.slice()

截取Array的一部分,返回一一个新数组,类似于String中的substring

3push() pop()
push:
压入到尾部
pop:
弹出尾部的一一个元素
 arr.push(1, 2)
 arr.pop()
4、unshift() , shift()头部
unshift:
压入到头部
shift:弹出头部的 -一个元素
5.排序sort()
(3) ["B", "C","A"]
arr.sort()
(3) ["A","B" ,"C"]
6.元素反转reverse()
(3) ["A","B" ,"C"]
arr.reverse()
(3) ["B", "C","A"]
concat()1
   [ 1, 2, 3, 4, 5, 1 ]
          console.log(arr.concat([1, 2, 3]));
   [ 1, 2, 3, 4, 5, 1, 1, 2, 3 ]

注意: concat ()并没有修改数组,只是会返回一个新的数组

8、连接符join

打印拼接数组,使用特定的字符串连接

console.log(arr.join("-"));

1-2-3-4-5-1
9.多维数组
arr = [[1,2],[3,4],["5","6"]];
arr[1] [1]
4

对象

 var Pserson = {
            name: '徐凤年',
            age: 18,
            socre: 75,
            aihao: "喜欢"
        }
1.动态的删减属性,通过delete删除对象的属性
 delete Pserson.age
2.动态的添加,直接给新的属性添加值即可
Pserson.age = "1111111";
3.判断属性值是否在这个对象中!XXX in xXx!
'age' in Pserson 

true
4.判断一个属性 是否是这个对象自身拥有的hasOwnProperty()
Pserson.hasOwnProperty("toString")
false
Pserson.hasOwnProperty("age")
true

流程控制

if
 var age = 3;
        if (age > 3) { //第一个判断
            alert("haha");
        } else if (age < 5) { //第二个判断
            alert("kuwa~");
        } else { //否则,,
            alert("kuwa~");
        }
while循环
        var age = 3;
        while (age < 100) {
            age = age + 1
            console.log(age);
        }
for循环
    for (let i = 0; i < 100; i++) {
            console.log(i);
        }
forEach循环
   var age = [1,2,3,5,74,43,24,63]
        age.forEach(function (value) {
            console.log(value);
        })
for...in

不知道数量的情况下

//for(var index in object){}

var age = [1,2,3,5,74,43,24,63]

        for (const num in age) {
            if (age.hasOwnProperty(num)) {
               console.log(age[num]);
                
            }
        }

Map 和 Set es6新特性

Map 集合
var map = new Map([['tom' ,100],['jack' ,90],['haha' ,80]]);
var name = map. get('tom'); //通过key获 得value!
map . set( ' admin' ,123456); //新增或修改!
map. delete("tom"); //删除!
Set:无序不重复的集合
 var set = new Set([3, 3, 3, 1, 2])
        console.log(set);
        Set(3) [ 3, 1, 2 ]
        
        set. add(2); //添加!
set. delete(1); //删除!
console.1og(set. has(3)); //是否包含某个元素!

iterator es6新特性

for of

遍历数组
var arr = [3,4,5]
for (var x of arr){
console.1og(x)
遍历map
  var map = new Map([['tom', 100], ['jack', 90], ['bask', 90]]);
        for (let x of map) {
            console.log(x);
        }
遍历set
  *var* set = new *Set*([3, 3, 3, 1, 2])

​    *for* (*let* x of set) {

​      console.*log*(x);

​    }

4.函数

绝对值函数

js 复制代码
 function abs(x) {
   //  手动抛出异常
     *if* (typeof x !== 'number') {

​        *throw* 'Not a Number'

​      }
            if (x >= 0) {
                return x;

            }
            else {
                return -x;
            }

        }

定义方式二

js 复制代码
  var abs = function(x){
      if (x >= 0) {
                return x;

            }
            else {
                return -x;
            }
  }

function(x){ ... }这是一个匿名函数。但是可以把结果赋值给abs,通过abs就可以调用函数!

以前arguments

是一个JS免费赠送的关键字;

代表,传递进来的所有的参数,是一个数组!

现在rest

ES6引入的新特性,获取除了已经定义的参数之外的所有参数~ ...

 function aaa(a, b, ...rest) {
            console.log("a=>" + a);
            console.log("b=>" + b);
            console.log(rest);
        }

rest参数只能写在最后面,必须用...表示

4.2变量作用域

在javascript中,var 定义变量实际是有作用域的。

假设在函数体中声明,则在函数体外不可以使用~

    function aj() {
            var x = 1;
            x = x + 1;
        }
        x = x + 2; 

内部函数可以访问外部函数,反则不行

function aj2(){
            var y;
            
            var x = 'x' + y;
            console.log(x);
            y = 'y';
        }
结果: xundefined

说明;js执行引擎,自动提升了y的声明,但是不会提升变量y的赋值;

全局函数

        var x = 1;
        function f() {
            console.log(x);
        }
        f()
        console.log(x);
全局对象 window

Javascript实际上只有一个全局作用域,任何变量(函数也可以视为变量),假设没有在函数作用

范围内找到,就会向外查找,如果在全局作用域都没有找到,报错RefrenceError

由于我们所有的全局变量都会绑定到我们的window.上。如果不同的js文件,使用了相同的全局变

量,冲突~>如果能够减少冲突>?

把自己的代码全部放入自己定义的唯一 空间名字中, 降低全局命名冲突的问题~

   var XuApp = {};


        XuApp.name = "xu";
        XuApp.add = function (a) {
            return a + b;
        }
局部作用域let

ES6 let关键字,解决局部作用域冲突问题!

const定义常量 ES6
const PI= '3.14';
console.log(PI);
PI = '123'
4.3方法
   var Xufeng = {
            name: '许芬概念',
            birth: 2003,
            age: function () {
                var now = new Date().getFullYear()
                return now - this.birth
            }
        }
        //Xufeng.age属性
        //Xufeng.age()方法
        console.log(Xufeng.age());
        
        //或者
             function gedtage() {
            //今年 - 出生的年
            var now = new Date().getFullYear()
            return now - this.birth
        }

        var Xufeng = {
            name: '许芬概念',
            birth: 2003,
            age: gedtage
        }
        console.log(Xufeng.age());

this是无法指向的,是默认指向调用它的那个对象;

apply

在js中可以控制this指向!

   function gedtage() {
            //今年 - 出生的年
            var now = new Date().getFullYear()
            return now - this.birth
        }

        var Xufeng = {
            name: '许芬概念',
            birth: 2003,
            age: gedtage
        }
        // console.log(Xufeng.age());
        gedtage.apply(Xufeng, [])//this指向了XUfeng这个对象 参数为空
        console.log(gedtage.apply(Xufeng, []));

内部对象

Date
 var now = new Date();
         now.getFullYear();//年
         now.getMonth();//月
         now.getDate();//日
         now.getDay();//星期几
         now.getHours()//时
         now.getMinutes();//分
         now.getSeconds()//秒
         now.getTime();//时间戳 全世界统一1970 1.1 0: 00: 00 

可以通过时间戳得到当前时间

new Date()
new Date()
console.log(new Date(1646622110294))
转化时区
now.*toDateString*()

JSON

json是什么

●JSONlavaScript Object Notation, JS对象简谱)是- -种轻量级的数据交换格式。

●简洁和清晰的层次结构使得JISON成为理想的数据交换语言。

●易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

json字符串和js对象的转换

对象转换为json字符串*

JSON.stringify()

json 字符串转换为对象

JSON.parse({})

   var user = {
            name: 'xufengnian',
            age: 3,
            sex: '男'
        }
        //对象转换为json字符串
        var jsons = JSON.stringify(user)

        //json  字符串转换为对象
        var obj = JSON.parse({
            "name": "xufengnian",
            "age": "3",
            "sex": "男"
        })

ajax

●原生的js写法 xhr异步请求

●jQuey封装好的方法$("#name")ajax(")

●axios 请求

面向对象编程

原型:

proto

proto__这是每个对象(除null外)都会有的属性,叫做__proto,这个属性会指向该对象的原型。

js 复制代码
   var student = {
            name: "xufengnian",
            age: 3,
            run: function () {
                console.log(this.name + "run...");
            }
        }

        var xiaoming = {
            name: 'xiaoming'
        }
        //原型对象
        xiaoming.__proto__ = student;
        //xiaoming的原型是student __proto__原型指向



        var Bird = {
            fly: function () {
                console.log(this.name + "fly------");
            }
        }

        xiaoming.__proto__ = Bird 
prototype

在JavaScript中,每个函数都有一个prototype属性,这个属性指向函数的原型对象。

  function student(name) {
            this.name = name
        }


        student.prototype.hello = function () {

            alert("hello")

        }
三、constructor

每个原型都有一个constructor属性,指向该关联的构造函数。

class继承

ES6引入

原型对象

定义一个类,属性,方法

javascript 复制代码
  class student {

            constructor(name) {
                this.name = name;
            }
            hello() {
                alert("hello")
            }
        }

        var xiaoming = new student("xiaoming")
        var xiaohong = new student("xiaohong")

2,继承

             //定义一个学生的类
        class student {

            constructor(name) {
                this.name = name;
            }
            hello() {
                alert("hello")
            }
        }


        class Xiaostudent extends student {
            constructor(name,grade) {
                super(name);
                this.grade = grade;
            }

            mygrade(){
                alert('小朋友')
            }
        }

        var xiaoming = new student("xiaoming")
        var xiaohong = new Xiaostudent("xiaohong", 1)
原型链

proto

操作BOM对象

window

游览器内部高宽
window.innerHeight 

778  

window.innerWidth 

734 
游览器外部高宽

window.outerHeight 

878 

window.outerWidth 

1550

封装了游览器的信息

navigator.userAgent
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0"
navigator.appName
"Netscape"
navigator.userAgent
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0"
navigator.platform
"Win32"

screen

代表屏幕尺寸

screen.width
1536
screen.height
864

location

location代表当前页面的URL信息

document

document代表当前的页面,HTML DOM文档树

document.title
"新标签页"
document.title = "徐凤年"
"徐凤年"

获取具体的文档树结点

html 复制代码
  <ul id="app">
        <li>java</li>
        <li>java</li>
        <li>java</li>
    </ul>
    <ul class="app">
        <li>java</li>
        <li>java</li>
        <li>java</li>
    </ul>
    <script>
        var dl = document.getElementById('app');
        var dl1 = document.getElementsByClassName('app')
获取cookie
document.cookie

"BAIDUID=4D5B38478CCF1B289A8C4B0AE25A5264:FG=1; BIDUPSID=4D5B38478CCF1B286B12370080EF47FB; PSTM=1631062268; MCITY=-%3A; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; 

history

history代表游览器的历史记录

history.forward()//前进
history.back()//后退

操作DOM对象

DOM:文档对象模型:

游览器网页就是一个DOM结构

标签选择器

document.getElementsByTagName();

id选择器

document.getElementById();

类选择器

document.getElementsByClassName();

获得dom结点

  //对应css选择器
        var h1 = document.getElementsByTagName('h1');
        var p1 = document.getElementById('p1');
        var p2 = document.getElementsByClassName('p2');
        var father = document.getElementById('father')

        var childrens = father.children;//获取父节点下的所有子节点
        //father.firstChild 获取第一个结点
        //father.lastChild 获取最后一个结点

更新dom结点

  <div id="id1"></div>

    <script>

        var id1 = document.getElementById('id1')
        id1.innerText = '234';
        id1.innerHTML = '<strong>123</strong>'

    </script>
操作文本

innerText

innerHTML

id1.innerText = '234'; 修改文本的值

id1.innerHTML = '< strong>123</ strong>'; 可以解析html标签

操作css
css 复制代码
 id1.style.color = 'red';
        id1.style.fontSize = '27px';
        id1.style.padding = '10px'

删除结点

删除节点的步骤:先获取父节点, 在通过父节点删除自己

html 复制代码
    <div id="father">
        <h1>
            标题一
        </h1>
        <p id="p1">p1</p>
        <p class="p2">p2</p>
    </div>
  var self = document.getElementById('p1');
        var father = p1.parentElement;
        father.removeChild(self);
        
        
        father.removeChild(father.children[0])
father.removeChild(father.children[1])
Uncaught TypeError: Node.removeChild: Argument 1 is not an object.
    <anonymous> debugger eval code:1

注意:删除多个节点的时候,children是在时刻变化的,删除节点的时候一 定要注意!

插入结点

html 复制代码
 <p id="js">javascript</p>

    <div id="list">
        <p id="se">javase</p>
        <p id="ee">javaee</p>
        <p id="me">javame</p>
    </div>

    <script>
        var js = document.getElementById('js')
        var list = document.getElementById('list')
        //追加至最后一个
        list.appendChild(js);

创建结点

html 复制代码
   //通过js创建一个新的结点
        var newP = document.createElement('p')
        newP.id = 'newP';
        newP.innerText = 'wngrui'
        list.appendChild(newP)
  var js = document.getElementById('js')
        var list = document.getElementById('list')
        list.appendChild(js);

        //通过js创建一个新的结点
        var newP = document.createElement('p')
        newP.id = 'newP';
        newP.innerText = 'wngrui'
        list.appendChild(newP)
        //创建一个标签结点
        var myscipt = document.createElement('script');
        myscipt.getAttribute('type', 'text/javascript')

        list.appendChild(myscipt);

        //创建一个style
        var mystyle = document.createElement('style');//创建一个空的style
        mystyle.setAttribute('type', 'text/css');

        mystyle.innerHTML = 'body{background-color:pink;}'; //设置一个标签内容

        document.getElementsByTagName('head')[0].appendChild(mystyle);

insertBefore(newNode,targetNode)

新节点,插入到谁的前面

  var ee = document.getElementById('ee');
        var js = document.getElementById('js');
        var list = document.getElementById('list');

        list.insertBefore(js, ee)

表单验证

操作表单

    <form action="post">
        <span>用户名</span> <input type="text" id="username">

        <span>性别</span>
        <input type="radio" name="sex" value="man" id="boy">男
        <input type="radio" name="sex" value="women" id="girl">女

        
    </form>
    <script>
        var input_text = document.getElementById('username');
        var boy_radio = document.getElementById('boy');
        var girl_radio = document.getElementById('girl');
        //得到输入框的值
        input_text.value;
        //修改输入框的值
        input_text.value = "123"
        //对于单选框,多选框等等固定的值,boy_ radio. value只能取到当前的值

        boy_radio.checked = "true"
        girl_radio.checked = "true"//查看返问的结果,是否为true,如果为true,则被选中

表单密码验证,md5

工具类

 <!-- md5工具类 -->
    <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
    <!--
表单绑定提交事件
onsubmit=绑定一" 个提交检测的两数,true,
false .
将这个结果返回给表单,使用onsubmit接收
    -->
    <form action="https://www.baidu.com/" method="post" onsubmit="return aaa()">
        <p><span>用户名</span> <input type="text" id="username" name="username"></p>

        <p><span>密码</span> <input type="text" id="password" name="password"></p>
        <input type="hidden" id="md5-password" name="password">
        <button type="submit"> 提交</button>
    </form>

    <script>
        function aaa() {
            var uname = document.getElementById('username');
            var upassword = document.getElementById('password')
            //console.log(uname.value);
            // console.log(upassword.value);

            var md5pwd = document.getElementById('md2-pawssword')
            //upassword.value = "****"
            md5pwd.value = md5(upassword.value)

            return true;
        }
    </script>

jQuery

$(选择器).事件()

    <a href="" id="text-jquery">点击</a>
    <script>
        $('#text-jquery').click(function () {
            alert('nihao')
        })

jQuery选择器

    $('p').click();//标签选择器
        $('#id1').click();//id选择器
        $('.class1').click();//class选择器

jQuery工具栈https://jquery.cuishifeng.cn/

事件

鼠标事件,键盘事件

  <!-- 要求获取鼠标当前的一个坐标 -->
    mouse: <span id="mouseMove"></span>
    <div id="divMove"></div>
    这里移动鼠标
    <script>
        $(function () {
            $('#divMove').mousemove(function (e) {
                $('#mouseMove').text('x' + e.pageX + 'y' + e.pageY)
            })
        })

操作DOM

  $('#test-ul li[name=python]').text();//获得值
$('#test-ul li[name=python]').text('设置值');
  $('#test-ul').html()//获得值
  $('#test-ul').html('')//设置值

css操作

 $("ul").css("color", "red");

元索的显示和隐藏:本质display :none

 $('#test-ul li[name=python]').show();
  $('#test-ul li[name=python]').hide();

md5(upassword.value)

        return true;
    }
</script>




## jQuery

[外链图片转存中...(img-3JexNuoV-1709561850515)]

###  $(选择器).事件()

<a href="" id="text-jquery">点击</a>
<script>
    $('#text-jquery').click(function () {
        alert('nihao')
    })




### jQuery选择器

$('p').click();//标签选择器
    $('#id1').click();//id选择器
    $('.class1').click();//class选择器




jQuery工具栈https://jquery.cuishifeng.cn/



### 事件



鼠标事件,键盘事件

[外链图片转存中...(img-ANhHFDRS-1709561850517)]

mouse: <span id="mouseMove"></span>
<div id="divMove"></div>
这里移动鼠标
<script>
    $(function () {
        $('#divMove').mousemove(function (e) {
            $('#mouseMove').text('x' + e.pageX + 'y' + e.pageY)
        })
    })




### 操作DOM

$('#test-ul li[name=python]').text();//获得值

$('#test-ul li[name=python]').text('设置值');

$('#test-ul').html()//获得值

$('#test-ul').html('')//设置值

### css操作

$("ul").css("color", "red");

### 元索的显示和隐藏:本质display :none

$('#test-ul li[name=python]').show();

$('#test-ul li[name=python]').hide();

复制代码
相关推荐
qiyi.sky6 分钟前
JavaWeb——Vue组件库Element(3/6):常见组件:Dialog对话框、Form表单(介绍、使用、实际效果)
前端·javascript·vue.js
煸橙干儿~~9 分钟前
分析JS Crash(进程崩溃)
java·前端·javascript
哪 吒11 分钟前
华为OD机试 - 几何平均值最大子数(Python/JS/C/C++ 2024 E卷 200分)
javascript·python·华为od
我是陈泽14 分钟前
一行 Python 代码能实现什么丧心病狂的功能?圣诞树源代码
开发语言·python·程序员·编程·python教程·python学习·python教学
安冬的码畜日常19 分钟前
【D3.js in Action 3 精译_027】3.4 让 D3 数据适应屏幕(下)—— D3 分段比例尺的用法
前端·javascript·信息可视化·数据可视化·d3.js·d3比例尺·分段比例尺
优雅的小武先生25 分钟前
QT中的按钮控件和comboBox控件和spinBox控件无法点击的bug
开发语言·qt·bug
邓校长的编程课堂30 分钟前
助力信息学奥赛-VisuAlgo:提升编程与算法学习的可视化工具
学习·算法
虽千万人 吾往矣31 分钟前
golang gorm
开发语言·数据库·后端·tcp/ip·golang
创作小达人34 分钟前
家政服务|基于springBoot的家政服务平台设计与实现(附项目源码+论文+数据库)
开发语言·python
郭二哈36 分钟前
C++——list
开发语言·c++·list