JavaScript初了解

最近想写一个web应用,打算稍微学一下。

本文是个人在学习过程中的笔记,目的是分享。

本文的阅读对象是已经有一门编程语言的基础,想进一步大致了解JS语言的读者
本文章不适合完全零基础且对前端毫无概念的伙伴。

1、变量和数据类型

//number数值型
var myNum = 10
//字符型
var myStr = 'abc'
//String字符串型
var myName = "zhangsan"
//boolean布尔型
var myBool = true
//空
var myNull = null
//undefiend变量未定义
var myUn

//控制台打印
console.log(myName)

2、运算

var sum = 2 + 3

var resultStr = 'Hello ' + 'World'

var isTrue = 3 > 2

console.log(3 === '3')

3、逻辑分支

if (2 > 1) {
    console.log("run....")
}

var age = 18
if (18 >= age) {
    console.log("少年")
} else if (18 < age <= 35) {
    console.log("青年")
} else if (35 < age <= 60) {
    console.log("中年")
} else {
    console.log("老年")
}

var result = 0
for (var i = 0; i < 100; i++ ) {
    if (i % 2 === 0) {
        result = result + i
    }
}
console.log(result)

4、函数

function getSum() {
    console.log("start")
    var result = 0
    for (var i = 0; i < 100; i++ ) {
        result = result + i
    }
    return result
    console.log("end")
}
getSum()


function getSumWithCondition(start, end, fn){
    var sum = 0
    for (var i = start;i <= end; i++) {
        if (fn(i)) {
            sum += i
        }
    }
    return sum
}
var result = getSumWithCondition(1, 100, function(n) {
    if (n % 2 ===0) {
        return true
    }
    return false
})
console.log(result)

5、数组

var myArray = [1,2,3,4,5]
console.log(myArray.length)
console.log(myArray[0])
myArray.push(6)
myArray.unshift(0)

myArray.forEach(function (item, index) {
    console.log(item, index)
})

6、对象

var obj = {
  name: "zhangsan",
  age: 18
}
console.log(obj)
> {name: 'zhangsan', age: 18}
console.log(obj.name)
> zhangsan
console.log(obj['name'])
> zhangsan

for (var k in obj) {
  console.log(obj.name)
}
> zhangsan

7、ES6

//1、变量与常量
let num = 10
const BASE_URL = "http://open.ai"


//2、模版字符串
const str1 = 'abc'
const str2 = `${str1}efg`


//3、解构赋值
const [a, b, c] = [1, 2, 3]
console.log(a,b,c)

const {name: userName, age, ...otherInfo} = {
    name: "zhangsan",
    age: 18, 
    mail: "test123@qq.com",
    gender: "male"
}
console.log(userName,age,otherInfo)
> zhangsan 18 {mail: 'test123@qq.com', gender: 'male'}

//4、数组和对象的扩展
//4、1扩展运算符
const arr1 = [1,2,3]
const arr2 = [4,5,6]
const arr3 = [...arr1, ...arr2, 7, 8]
console.log(arr3)
> [1, 2, 3, 4, 5, 6, 7, 8]

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}
const obj3 = {
  c: 3,
  ...obj1,
  ...obj2
}
console.log(obj3)
> {c: 3, a: 1, b: 2}

//4.2 数组方法 Array.frome()
function fn(){
    console.log(arguments)
    //arguments.push(5)
    var bb = Array.from(arguments)
    bb.push(5)
    bb.forEach(function (item){
        console.log(item)
    })
}
fn(1,2,3,4)

//4.3 对象的方法Object.assign()
const objA = {
    name: "zhangsan",
    age: 18
}
const objB = {
    gender: 'male'
}

const objC = Object.assign({},objA,objB)
objC.name = "lisi"
console.log(objA,objB,objC)

> {name: 'zhangsan', age: 18} {gender: 'male'} {name: 'lisi', age: 18, gender: 'male'}


//5、class
class A {
    //构造方法
    constructor (name, age) {
        this.name = name
        this.age = age
    }
    show () {
        console.log(`My name is ${this.name},my age is ${this.age}`)
    }
}
const a1 = new A('zhangsan',20)
console.log(a1)
> {name: 'zhangsan', age: 20}
a1.show()
> My name is zhangsan,my age is 20

//继承
class B extends A {
    constructor (name, age, gender) {
        super(name,  age, gender)
        this.gender = gender
    }
    sayHello () {
        console.log(`hello ${this.name}`)
    }
}
const b1 = new B('wangwu',20,'女')
console.log(b1)
b1.sayHello()
b1.show()
>  {name: 'wangwu', age: 20, gender: '女'}
> hello wangwu
> My name is wangwu,my age is 20


//6箭头函数(匿名函数的简写方式)
const getSum1 = function (n) {
    return n + 3
}
console.log(getSum1(10))

const getSum2 = n => n + 3
console.log(getSum2(10))
> 13

const getSum3 = (n1,n2) => n1 + n2
console.log(getSum3(10,4))

const getSum4 = (n1, n2, ...other) => console.log(n1,n2,other)
console.log(getSum4(10,4,12,14,55))
> 10 4 [12, 14, 55]

const getResult = arr => {
    let sum = 0
    arr.forEach(item => sum +=item)
    return sum
}
console.log(getResult([1,2,3,4,5]))
> 15

Promise Async

console.log('任务1.....同步')
setTimeout(() => {
    console.log('任务2.....异步')
},0)
console.log('任务3.....同步')
console.log('任务4.....同步')

const p1 = new Promise((resolve, reject) => {
    //resolve("成功的数据")
    reject("失败的数据")
})
console.log(p1)
p1.then(data => {
    console.log(data)
}).catch(err => {
     console.log(err)
})

Aync是基于Promise的简化

//1  准备一个返回Promise对象的函数
function asyncTask () {
    return new Promise((resolve, reject) => {
        //假装有一些业务
        const isSuccess = true
        if (isSuccess) {
            resolve("任务2.......成功")
        }else{
            reject("任务2.......失败")
        }
    })
}
//2 为使用await的杉树添加async
async function main(){
    console.log("任务1")
    const data = await asyncTask()
    console.log(data)
    console.log("任务3")
}
main()

Proxy 代理对象

//更新元素 冗余代码过多
const obj = {name: 'zhangsan', age: 18}
const container = document.getElementById('container')
container.textContent = obj.name
obj.name = 'wangwu'
container.textContent = obj.name


const objA = {
    name: "zhangsan",
    age: 18
}
const container = document.getElementById('container')
container.textContent = objA.name
const p1 = new Proxy(objA,  {
    get(target, property) {
        return obj[property]
    },
    set (target, property, value) {
        obj[property] = value
        container.textContent = objA.name
    }
})
console.log(p1.name)
p1.age = 22

Module: ESM(浏览器) CommonJS(Node.js)

moduleA.js

export const aTitle = "a标题"
export function aFn() {
    console.log('a模块的方法')
}

export default {
    name: "a模块"
}

moduleB.js

export const bTitle = "b标题"
export function bFn() {
    console.log('b模块的方法')
}

export default {
    name: "b模块"
}

index.js

import m1 from './moduleA.js'
import m2 from './moduleB.js'
import { aTitle, aFn } from './moduleA.js'
import { bTitle, bFn as bFunction } from './moduleB.js'

console.log(m1)
console.log(m2)

CommonJS

moduleC.js

module.exports = {
    name: 'zhangsan',
    age: 19
}

index.js

const m3 = require('./moduleC')

网络请求
AJAX

const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://jsonplaceholder.typicode.com/posts?name=zhangsan&age=19')
xhr.send()
xhr.onreadystatechange = function() {
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200){
        console.log(JSON.pare(xhr.responeText))
    }
}
const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://jsonplaceholder.typicode.com/posts')
xhr.setRequestHeader('Content','application/x-www-form-urlencoded')
xhr.send('name=zhangsan&age=19')
xhr.onreadystatechange = function() {
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200){
        console.log(JSON.pare(xhr.responeText))
    }
}

Axios
包需要引入

axios.get('http://jsonplaceholder.typicode.com/posts?name=zhangsan&age=19')

(async () => {
    const res1 = await axios.get('http://jsonplaceholder.typicode.com/posts?name=zhangsan&age=19')
    
    const res2 = await axios.post('http://jsonplaceholder.typicode.com/posts', {
        name: 'zhangsan',
        age: 19
    })
    console.log(res.data)
})


(async () => {
    const http = axios.create({
        bashURL: 'http://www.baidu.com/api/v1'
    })
    const res1 = await http.get('/name',{
        name: 'zhangsan',
        age: 19
    })
    console.log(res1.data)
})

Fetch API

fetch('http://jsonplaceholder.typicode.com/posts?name=zhangsan&age=19')
.then(res => {
    if(res.ok){
        return res.json()
    }
})
then(data => {
    console.log(data)
})


fetch('http://jsonplaceholder.typicode.com/posts',{
    method: 'POST',
    headers: {
        'Content-Type': 'application/json' 
    },
    body: JSON.stringify({
        name: 'zhangsan',
        age: 19
    })
})
.then(res => {
    if(res.ok){
        return res.json()
    }
})
then(data => {
    console.log(data)
})

参考

posted @ 2024-04-17 19:52  西二旗老实人  阅读(3)  评论(0编辑  收藏  举报