(前端面试)每日5题

1、ES6中for in 和for of的区别

        a、for in 获取对象键名,for of获取对象键值

        b、for-in,主要是为了遍历对象而产生的,不适用于遍历数组,for-of,循环可以用来遍历数组,类数组对象,字符串,...

        c、for-in会遍历对象整个原型链,for-of只会遍历当前对象

2、JS中ajax(Async Javascript and XML)的原理是什么?如何实现

        原理:通过XMLHttpRequest对象来向服务器发送异步请求,从服务起获取数据,然后用js来操作DOM去更新页面

        实现过程:

  创建 Ajax的核心对象XMLHttpRequest对象

          new XMLHttpRequest()实例化对象

  通过 XMLHttpRequest 对象的open() 方法与服务端建立链接

           new XMLHttpRequest().open(method:表示请求方式,url:服务器的地址)

   构建请求所需的数据内容,并通过XMLHttpRequest 对象send() 方法发送给服务器

           new XMLHttpRequest().send(body:发送的数据)

   通过 XMLHttpRequest 对象提供的 onreadystatechange 事件监听服务器端的通信状态

            new XMLHttpRequest().onreadystatechange主要监听的属性是实例化对象中readyState(五个状态)

             0: open()未调用 1: send()未调用 2: send()已经调用,响应头和响应状态已经返回

             3: 响应体正在下载,responseText(接收服务端响应的结果)获取到部分的数据

             4:整个请求过程已经完毕

    将处理结果更新到HTML页面中

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E8%B5%A3%E5%B7%9E&ci=217&channelId=4');
xhr.send(null);
xhr.onreadystatechange = function() {
    if(xhr.readyState === 4) {
        if(xhr.status >= 200 && xhr.status < 300) {
            let obj = JSON.parse(xhr.responseText);
            obj.result.forEach(item => {
                var div = document.createElement('div');
                div.innerHTML = item.name;
                document.querySelector('body').appendChild(div);
            });
        }else if(xhr.status >= 400) {
            console.log('错误信息' + xhr.status);
        }
    }
}

3、JS中如何封装一个AJAX请求

function ajax(options) {
    //创建XMLHttpRequest对象
    const xhr = new XMLHttpRequest();
    //初始化参数的内容
    options = options || {};
    options.type = (options.type || 'GET').toUpperCase();
    options.dataType = options.dataType || 'json';
    const params = options.data;
    //发送请求
    if(options.type === 'GET') {
        //第三个参数 async: 布尔值,表示是否异步执行操作
        xhr.open('GET', options.url + '?' + getParams(params), true);
        xhr.send(null);
    }else if(options.type === 'POST') {
        xhr.open('POST', options.url, true);
        xhr.send(params);
    }
    //接收请求
    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
            if(xhr.status >=200 && xhr.status < 300) {
                //responseText 字符串形式的响应数据
                //responseXMl XML形式的响应数据
                options.success(xhr.responseText, xhr.responseXML)
            }else{
                options.fail('参数错误' + status);
            }
        }
    }
};
ajax({
    type: 'get,
    dataType: 'json',
    data: {
        limit: 10,
        age: 25,
        name: 'xiaofei',
        height: 183
    },
    url: 'http://localhost:3000/paersonalized',
    success: function(text, xml) {
        //请求成功之后的回调函数
        console.log(JSON.parse(text));
    },
    fail: function(status) {
        //请求失败之后的回调函数
        console.log(status);
    }
});
//对参数做处理
function getParsms(data) {
    let arr = [];
    for(let key in data) {
        arr.push(`${key} = ${data[key]}`);
    }
    console.log(arr);
    return arr.join('&');
};
getParams({limit: 10, age: 25});

4、ES6中使用Promise封装AJAX

function getJSON(url) {
    return new Promise((resolve, reject) => {
        //创建一个实例对象
        let xhr = new XMLHttpRequest();
        //新建一个http请求
        xhr.open('GET', url, true);
        //发送http请求
        xhr.send(null);
        //设置状态的监听函数
        xhr.onreadystatechange = function() {
            if(xhr.readyState !== 4) return;//表示请求完成
            if(xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.responseText);//请求结果
            }else{
                reject(new Error(xhr.statusText));
            }
        }
        //设置错误监听函数
        xhr.onerror = function() {
            reject(new Error(xhr.statusText));
        }
        //设置响应数据类型
        xhr.responseType = 'json'
    })
};

getJSON('http://localhost:3000/personalized?limit=10').then((value) => {
            console.log(JSON.parse(value));
        }).catch((reason) => {
            console.log(reason);
        })

5、JS中"use strict"是什么

        严格模式

        1、使调试更加容易

        2、变量在赋值之前必须要声明,防止意外的全局变量

        3、取消this的强制转换

var age = 20;
function fun() {
    console.log(this.age);//报错
};
fun();

        fun.apply(null)  引用null或未定义的值,this值会自动强制到全局变量,严格模式下,报错this不会指向window

        4、不允许参数重名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值