JavaScript 的基础用法

JS 的使用

定义变量

// 单行注释  /*
// */ 多行注释

// 声明变量使用var 关键字
var $ = '2';

var a = 2;
let aa = a;  // 解决变量提升
const AAA = 11;  // 定义常量 

console.log(a);
var str = 'hollo world';

//   全局对象 
window.str = 'hollo world'

/    先声明 后定义
//     var a;
//     a = 2;
//     alert(a);
//    声明多个变量
var a = '2',b = 4,c = true;

console.log(a);
// 打印类型
console.log(typeof a);
console.log(typeof b);
console.log(typeof c);

var str = '您真好';
//NaN 一个特殊的类型 Not a number  但是 它是一个数值类型
console.log(parseInt(str));  
console.log(typeof  parseInt(str))

//如果 变量 是数值 返回为false
console.log(isNaN(2));
//只保留整数
console.log(parseInt(5.8)); 


//未定义的数据类型
var a;
console.log(a);
console.log(typeof a);
// 行内填写 
<button onclick="alert('打开百度')">打开百度</button>
// 
alert()  // 弹窗
typeof a  // 打印类型
parseInt(str) // 转为数字  无数字的的字符串 为 NaN  not a namber  只保留整数
isNaN(2) // 是数字返回 false
undefined  // 未定义
==  比较值
===  向当于python 中的  is

// 比较对象
a instanceof b

// 拼接字符创
'aaa' + "bbb"  ES5
// ES6
var name = 'zhangfei'
var b = `我叫${name}`
// 数字转字符串  
1234 + ""
// 强转字符串 
string(int)  int.tostring()
// 字符串转数字
Number(string)  parseFloat(string)
//console.log(7/0)  VM85:1 Infinity

// 三元运算
1<2 : (真:假)   
if (1>2) console.log('22')
  • 行内的 测试语句

<!--行内的js  alert() console.log()  测试语句-->
    <button onclick = 'alert("点我了")'>点我</button>
    <button onclick = 'console.log("点我了")'>点我</button>

运算符

    var a = 5;
    //先去赋值 后++
    var b = a++;
    //先++  将a的值 赋值给b
    var b = ++a;
    console.log(a);
    console.log(b);

    var x = 6;
    var y = '6';
    //比较的是值 等价于  true
    console.log(x==y);
    //相当于python中is  等同与  false
    console.log(x===y);

字符串拼接

// + 拼接字符串  ES5
var name = '张飞';
var am = '章子怡';
// 字符串拼接
var str = "你好" + name + "我叫" + am
var fullStr = str;
console.log(fullStr);

//    ES6的拼接字符串  `` tab键上面的反引号 变量用${变量名}
var str2 = `你好${name}我叫${am}`
//隐式转换 一个数值+一个字符串 相当于拼接字符串
var a = '1';
var b = 2
console.log(a+b);

数据类型转换

var a = 5;
//强制类型转换
//构造函数
console.log(String(a));
console.log(a.toString());
//字符串转数值类型
var numStr = '7788.44563563563535616743516748146148914189489';
console.log(Number(numStr));
console.log(parseFloat(numStr));

//   float 单精度 随着小数点后的位数 越多 不精准  double 随着小数点后的位数 越多 不精准 但是它要比float精准

//    1.1111111111111111111111111111  1.111111119098000000    1.1111111111111189080000

var b = 7 / 0;
console.log(b);
console.log(typeof  b);

var b1 = '123'; //true
var b2 = 0;    //false
var b3 = -123;  //true

var b4 = Infinity;  //true
var b5 = NaN;  //fasle

var b6;     //undefined  false
var b7 = null;
console.log(Boolean(b7));

流程控制

if(条件){
    代码块
}else if(条件){
    代码块
}else{
    代码块
}

// console.log(0&&1 || 2&&3);
// 三元运算
console.log( 1 < 2 ? '真的' : '假的');
if(1<2) console.log(2);


// switch 开关 流程控制
var weather = '雨天';
switch (weather){
    case '晴天':
        console.log('今天天气很好');
        break;
    case '雨天':
        console.log('今天天气不好');
        break;
    case '下雪':
        console.log('今天天气也不好');
        break;
    default:
        console.log('天气都不好')
}


// 初始化循环变量
var i = 1;
while (i <= 10) { // 判断循环条件

    console.log(i);
    i++; //更新循环条件
}

//不管有没有满足while中的条件do里面的代码都会走一次
var a = 3;//初始化循环变量
do {
    console.log(a)
    a++;//更新循环条件
} while (a < 10){} //判断循环条件


// for 循环
var arr = ['张三','李四'];
for(var i = 0; i < arr.length;i++){
   console.log(arr[i])
}
//使用forEach()来遍历列表
arr.forEach(function(item,index){
    console.log(item,index);
})


常用内置对象

  • Array

// 字面量方式创建
var colors = ['red', 'color', 'yellow'];

//内置的构造函数  在js中使用new关键字来创建对象
var colors2 = new Array('a', 'b');
var colors3 = new Array();
colors3[0] = 'alex';

var newArr = colors2.concat(colors3);
//  在数组中添加或移除元素
//  删除:第一个参数表示 起始的位置 第二个参数删除的个数
//  添加:第二个参数是0,表示添加
arr.splice(0,1,items...)

// 给列表的 第一项插入 元素
color.unshift('green')
  • Date

var date = new Date();
console.log(date.getFullYear()); // 年
console.log(date.getMonth()+1);//月
console.log(date.getDate());//日
console.log(date.getDay());//星期
console.log(date.getHours());//时
console.log(date.getMinutes());//分
console.log(date.getSeconds());//秒

//本地时间
console.log(date.toLocaleString());
  • Math
var a = 3.003;
//向下取整
console.log(Math.floor(a));
//向上取整
console.log(Math.ceil(a));

//0~1 之间的随机小数
console.log(Math.random());

//   300 ~ 500 之间的随机数    min~max  公式: min+Math.random()*(max-min)
console.log(300+Math.random()*(500-300));

函数

//构造函数  使用new 关键字创建对象
// new Array()

function add(x,y){
    return console.log(x+y)
}
console.log(add(3,4));

// 伪数组  arguments
function fn(){
    console.log(arguments);  // Arguments(2)
    // arguments.push('吴老板');
    var arr = [];
    for(var i= 0; i < arguments.length;i++){
        console.log(arguments[i])  // alex
        arr.push(arguments[i])  // wusir
    }
    console.log(arr);  // Array(2)

    // console.log(['alex']);
}
fn('alex','wusir')

//普通函数
function  add2() {
    alert(2)
}
//函数对象  匿名函数  函数没有名字
var add = function() {
    alert(1)
}

add();
add2()

构造函数

// new Object()
//构造函数
function Person(name,age){
    this.name = name;
    this.age = age;
    this.fav = function(){
    }
}
var p = new Person('alex',19)

json 序列化

// 序列化 
var str = JSON.stringify('json数据')
// 反序列化
var obj = JSON.parse(str)

XHR 对象

// 1. 创建对象
var xhr = new XMLHttpRequest()
// 2. 连接
xhr.open('GET',url,true)
// 3. 发送数据
shr.send()
// 4. 回调函数
xhr.onreadystatechange = function (){}
xhr.readystate 

js 中的面向对象

  1. 使用Object或对象字面量创建对象
    // 构造函数创建对象
    let Person = new Object();
    Person.name = "张飞";
    Person.age = 18;
    Person.fun = function () {
        console.log(Person.name);
        console.log(Person.age);
    };
    Person.fun()

    // 字面量创建
    var Person = {
        name: "张飞",
        age: 18,
        fun: function () {
            alert(Person.name);
        }
    };
    Person.fun()
  1. 工厂模式创建对象
 function createPerson(name, age) {
        let person = new Object();
        person.name = name;
        person.age = age;
        person.fav = function () {
            console.log(this);
        }

        return person;
    }

      function createFruit(name, age) {
        let fruit = new Object();
        fruit.name = name;
        fruit.age = age;
        fruit.fav = function () {
            console.log(this);
        }

        return fruit;
    }

    var p1 = createPerson('alex',17);
    var f1 = createFruit('桃子',1);

// 比较对象
    console.log(p1 instanceof Object);
    console.log(f1 instanceof Object);
  1. 构造函数模式创建对象
 function Person(name,age){
        this.name = name;
        this.age = age;
        this.fav = function () {
            alert(this.name)
        }
    }

    function Fruit(name,age){
        this.name = name;
        this.age = age;
        this.fav = function () {
            alert(this.name)
        }
    }
//    创建对象 使用new关键字
    var p1 = new Person('alex',17);
    var f1 = new Fruit('桃子',17);
    console.log(p1 instanceof Object);
    console.log(f1 instanceof Object);
    console.log(p1 instanceof Person);
    console.log(f1 instanceof Fruit);
  1. 原型模式创建对象
function Person(name,age){
        this.name = name;
        this.age = age;
}
Person.prototype.fav = function () {
    console.log(this.name);
}
let p1 = new Person('alex',16);
let p2 = new Person('alex',16);

p1.fav();

//es6 使用class关键字来创建对象
class Furit{
    //初始化的构造器方法  相当于 __init__ 
    constructor(name='alex',age=16){
        this.name = name;
        this.age = age
    }
    //对象的单体模式 等价于fav:function(){}
    fav(){
        console.log(this.age);
    }
}

var f1 =  new Furit();
f1.fav();

ES6 中的函数

// 函数  字典方式创建

var person1 = {
    name: 'alex',
    fav: function () {
        //alex
        console.log(this); //person1
        console.log(this.name);
    }
}
person1.fav();

var person2 = {
    name: 'alex',
    fav: () => {
        //this的指向发生了改变 指向了 定义当前person2对象的父类
        console.log(this);
    }
}
person2.fav();
//1.模板字符串 `` tab键上面的反引号
let name = '国家'
let str = `符合${name}按规定干哈进口国打卡机的`
//2.let 声明局部变量,变量不提升,不允许重复声明 
const 声明常量 不允许修改

//3.箭头函数 function(a,b){return a+b} === (a,b)=>{return a+b}

//4.对象的单体模式
var person = {
    name:'xxx',
    //es5的函数写法
    showAge:function(){
         console.log(this);//person
    },
     showName:()=>{
        console.log(this);//window  定义person的对象 它的上下文
    },
    //对象的单体模式 es6的写法
    fav(){
        console.log(this);//指的是person对象
    }

}
/*
fav(){
    } 等价于
    fav:function(){

    }
    */

定时器

  • setTimeOut() 一次性定时器 3秒之后做一个件事情

     var a  =2;
        var b = 3;
        console.log(a,b);
        //异步操作
        setTimeout(function () {
            console.log('我出来了');
        },5000);
    
        var app = function(){
            console.log('app');
        }
        app();
    
    - setInterval(function(){},5000)  // 周期循环 可以用它来做js动画,注意要清除定时器
    - clearTimeOut(function(){},5000)  // 单循环
    - clearInterval(循环对象)
    

猜你喜欢

转载自www.cnblogs.com/zhang-zi-yi/p/10800432.html