Home  >  Article  >  Web Front-end  >  Sharing of JS interview question records in 2017 and 2018

Sharing of JS interview question records in 2017 and 2018

不言
不言forward
2018-04-26 14:47:334604browse

Sharing of JS interview question records in 2017 and 2018

This article brings you the sharing of JS interview question records in 2017 and 2018. Interested friends can take a look

Recommended related articles:The most complete collection of js interview questions in 2020 (latest)

##2017 interview Share (js interview question record)

1. The simplest question

    '11' * 2
    'a8' * 3
    var a = 2, b = 3;    var c = a+++b; // c = 5

2. A question about this

    var num = 10;    var obj = {        num:8,        inner: {            num: 6,            print: function () {                console.log(this.num);
            }
        }
    }
    num = 888;
    obj.inner.print(); // 6
    var fn = obj.inner.print;
    fn(); //888
    (obj.inner.print)(); //6
    (obj.inner.print = obj.inner.print)(); //888 这个点没有太理解,虽然答对了

3. Pre-parsing problem of var and function, As well as the issue of the order of variables and functions

    // 以下代码执行输出结果是什么
    function b () {        console.log(a);        var a = 10;        function a() {};
        a = 100;        console.log(a);
    }
    b();    function c () {        console.log(a);        function a() {};        var a = 10;
        a = 100;        console.log(a);
    }
    c();

    (function d (num) {        console.log(num);        var num = 10;
    }(100))

    (function e (num) {        console.log(num);        var num = 10;        function num () {};
    }(100))

    (function f (num) {        function num () {};        console.log(num);        var num =10
        console.log(num);
    }(100))    //仍然是预解析(在与解析过程中还要考虑一下当前变量的作用于)
    function m () {        console.log(a1); // underfined
        console.log(a2); // underfined
        console.log(b1); // underfined
        console.log(b2); // underfined
        if(false) {            function b1 (){};            var a1 = 10;
        }        if(true) {            function b2 (){};            var a2 = 10;
        }        console.log(a1); // underfined
        console.log(a2); // 10
        console.log(b1); // underfined
        console.log(b2); // function
    }
    m();    function n() {        if(2>1) {
            arr = 10;
            brr = 10;            let arr;            var brr;            console.log(arr);            console.log(brr);
        }
    }
    n(); // ReferenceError

At this stage, the browser only performs a preparatory process for parsing var, function, and function parameters. And in this "pre-parsing" process, there is a pre-parsing sequence, that is, the formal parameters of the function -> function -> var. Moreover, when the name is the same, the function is reserved and the later one overwrites the former one. If the pre-parsed result formal parameter has a value, it will be parsed to the value. If not, it will be underfined. The function will be parsed to the entire function body, and the variables will be underfined. There are no parameters in this question, so we will not discuss it first. Therefore, when this question is "pre-parsed", the function declaration weight will be increased first

4. An algorithm problem

There is a sorted array, such as [ 1,4,6,9,11,15,18], give you a new number, insert it into the array, and write a function

5. What is function throttling and what are its advantages (I have never understood this concept before, so I am confused)

The purpose of function throttling

It can be understood literally. Function throttling is used to throttle functions to optimize performance to a certain extent. For example, DOM operations require more memory and CPU time than non-DOM interactions. Attempting to perform too many DOM-related operations in succession can cause the browser to hang and sometimes even crash. This is especially likely to happen when using the onresize event handler in IE. When the browser is resized, the event will be triggered continuously. If you try to perform DOM operations inside the onresize event handler, its high frequency of changes may crash the browser. For another example, for our common search function, we usually bind the keyup event and search every time the keyboard is pressed. But our purpose is mainly to search every time we enter some content. In order to solve these problems, you can use timers to throttle functions.

Principle of function throttling

Some codes cannot be executed continuously and repeatedly without interruption. The first time the function is called, a timer is created to run code after a specified interval. When the function is called a second time, it clears the previous timer and sets another one. If the previous timer has already been executed, this operation has no meaning. However, if the previous timer has not yet been executed, it is actually replaced with a new timer. The purpose is to execute the function only after the request to execute it has been stopped for some time.
http://www.cnblogs.com/LuckyW...

6. Write a method to pass in two parameters (parentNode, childNode), requiring that if childNode is a descendant node of parentNode, Then it returns true, otherwise it returns false

7. What is the principle of DOM event flow, and what are the stages it is divided into?

Event capture in target stage event bubbling

8. What is the principle of DOM event delegation, what are its advantages and disadvantages

Principle of event delegation: event bubbling mechanism

Advantages

1. It can save a lot of memory usage, Reduce event registration. For example, it is very good to proxy all click events of li on ul.
2. It can be realized that when a new sub-object is added, there is no need to event bind it, which is especially suitable for dynamic content.

Disadvantages

The common applications of event proxies should be limited to For the above requirements, if all events are used as event agents, event misjudgment may occur. That is, events that should not be triggered are bound to events.

9. HTTP cache mechanism, and how to implement from cache in 200 status (indicating that the most contacted is 304 from cache) (used for optimization, have not been exposed to it, need to understand)

Meaning

Definition: Browser caching (Browser Caching) is to speed up browsing. The browser stores recently requested documents on the user's disk. When the visitor requests this page again, the browser can retrieve it from Documents are displayed on local disk, thus speeding up page viewing.

Function

The function of cache:
1. Reduce latency, make your website faster and improve user experience.
2. Avoid network congestion, reduce request volume, and reduce output bandwidth.

实现手段

Cache-Control中的max-age是实现内容cache的主要手段,共有3种常用策略:max-age和Last-Modified(If-Modified-Since)的组合、仅max-age、max-age和ETag的组合。

对于强制缓存,服务器通知浏览器一个缓存时间,在缓存时间内,下次请求,直接用缓存,不在时间内,执行比较缓存策略。
对于比较缓存,将缓存信息中的Etag和Last-Modified通过请求发送给服务器,由服务器校验,返回304状态码时,浏览器直接使用缓存。

10. 一个原型链继承的问题

    // 有一个构造函数A,写一个函数B,继承A
    function A (num) {        this.titileName = num;
    }
    A.prototype = {        fn1: function () {},        fn2: function () {}
    }

这个问题的关注点是B继承的A的静态属性,同时B的原型链中不存在A实例的titleName属性

11. 什么是虚拟dom

React为啥这么大?因为它实现了一个虚拟DOM(Virtual DOM)。虚拟DOM是干什么的?这就要从浏览器本身讲起

如我们所知,在浏览器渲染网页的过程中,加载到HTML文档后,会将文档解析并构建DOM树,然后将其与解析CSS生成的CSSOM树一起结合产生爱的结晶——RenderObject树,然后将RenderObject树渲染成页面(当然中间可能会有一些优化,比如RenderLayer树)。这些过程都存在与渲染引擎之中,渲染引擎在浏览器中是于JavaScript引擎(JavaScriptCore也好V8也好)分离开的,但为了方便JS操作DOM结构,渲染引擎会暴露一些接口供JavaScript调用。由于这两块相互分离,通信是需要付出代价的,因此JavaScript调用DOM提供的接口性能不咋地。各种性能优化的最佳实践也都在尽可能的减少DOM操作次数。

而虚拟DOM干了什么?它直接用JavaScript实现了DOM树(大致上)。组件的HTML结构并不会直接生成DOM,而是映射生成虚拟的JavaScript DOM结构,React又通过在这个虚拟DOM上实现了一个 diff 算法找出最小变更,再把这些变更写入实际的DOM中。这个虚拟DOM以JS结构的形式存在,计算性能会比较好,而且由于减少了实际DOM操作次数,性能会有较大提升

12. js基础数据类型和引用类型分别是什么?这个前提条件下写一个getType,返回相应的类型

1.基本数据类型(自身不可拆分的):Undefined、Null、Boolean、Number、String
2.引用数据类型(对象):Object (Array,Date,RegExp,Function)
ES6基本数据类型多了个symbol 据说这道题刷了百分之二十的人 感谢Abbyshen提出

function gettype(nm){    return Object.prototype.toString.call(nm);
}

13. dom选择器优先级是什么,以及权重值计算(一道老问题了)

1.行内样式 1000
2.id 0100
3.类选择器、伪类选择器、属性选择器[type="text"] 0010
4.标签选择器、伪元素选择器(::first-line) 0001
5.通配符*、子选择器、相邻选择器 0000

14. vue双向数据绑定的原理是什么

首先传输对象的双向数据绑定 Object.defineProperty(target, key, decription),在decription中设置get和set属性(此时应注意description中get和set不能与描述属性共存)
数组的实现与对象不同。
同时运用观察者模式实现wather,用户数据和view视图的更新

15. react和vue比较来说有什么区别

1 component层面,web component和virtual dom
2 数据绑定(vue双向,react的单向)等好多
3 计算属性 vue 有,提供方便;而 react 不行
4 vue 可以 watch 一个数据项;而 react 不行
5 vue 由于提供的 direct 特别是预置的 directive 因为场景场景开发更容易;react 没有
6 生命周期函数名太长 directive

16. git使用过程中,如果你在开发着业务,突然另一个分支有一个bug要改,你怎么办

git stash       //将本次修改存到暂存区(紧急切换分支时)git stash pop   //将所有暂存区的内容取出来

17. postcss的使用

18. 网页布局有哪几种,有什么区别

静态、自适应、流式、响应式四种网页布局
静态布局:意思就是不管浏览器尺寸具体是多少,网页布局就按照当时写代码的布局来布置;
自适应布局:就是说你看到的页面,里面元素的位置会变化而大小不会变化;
流式布局:你看到的页面,元素的大小会变化而位置不会变化——这就导致如果屏幕太大或者太小都会导致元素无法正常显示。
自适应布局:每个屏幕分辨率下面会有一个布局样式,同时位置会变而且大小也会变。

18. 执行下面代码

var a = {};var b = {key: 'b'};var c = {key: 'c'};var d = [3,5,6];
a[b] = 123;
a[c] = 345;
a[d] = 333;console.log(a[b]);  // 345console.log(a[c]);  // 345console.log(a[d]);  // 333

19.

    var R = (function() {        var u = {a:1,b:2};        var r = {            fn: function(k) {                return u[k];
            }
        }        return r;
    }());
    R.fn('a');  // 1

上述代码中如何获取匿名函数中的u

20. 不适用循环语句(包括map、forEach方法)实现一个100长度的数组,索引值和值相同的数组[0,1,2,3,4,5........99]

var arr = new Array(100);//方法1[...arr.keys()];//方法二Array.from(arr.keys());//方法三Array.from({length: 100});// 方法四 借助stringvar arr1 = new Array(101);var str = arr1.join('1,');
str = str.replace(/(1\,)/g, function ($0, $1, index) {    var start = '' + Math.ceil(index/2);    if(index e6af0fb823c143a40a71e960e513f6b6= 100) {        return arr;
    }
    arr.push(val);    return reduce(arr, val+1);
}var res = reduce([], 0)

21. 下面语句执行结果输出

var a = function (val, index) {    console.log(index);    return {        fn: function (name) {            return a(name, val);
        }
    }
}var b = a(0); // underfinedb.fn(1); // 0b.fn(2); // 0b.fn(3); // 0

22. 科普

1) dom节点的根节点是不是body
回答: 不是,dom节点的根节点是html(包含head和body,head中分为meta、title等。body又分为一组)

2)dom元素都会有offsetParent吗
回答: offsetParent属性返回一个对象的引用,这个对象是距离调用offsetParent的元素最近的(在包含层次中最靠近的),并且是已进行过CSS定位的容器元素。 如果这个容器元素未进行CSS定位, 则offsetParent属性的取值为根元素(在标准兼容模式下为html元素;在怪异呈现模式下为body元素)的引用。 当容器元素的style.display 被设置为 "none"时(译注:IE和Opera除外),offsetParent属性 返回 null。

3) [1,3,5]转译成字符串是什么
回答: '1,3,5'
调用toString方法,生成该字符串

4)li标签的祖级元素可以为li,父级元素也可以为例
回答: 错误

23. jsonp原理,jquery是怎么实现的,这样实现有什么好处和坏处

原理

在同源策略下;在某个服务器下的页面是无法获取到该服务器以外的数据的;Jquery中ajax 的核心是通过 XmlHttpRequest获取非本页内容,而jsonp的核心则是动态添加 3f1c4e4b6b16bbbd69b2ee476dc4f83a标签来调用服务器提供的 js脚本
当我们正常地请求一个JSON数据的时候,服务端返回的是一串 JSON类型的数据,而我们使用 JSONP模式来请求数据的时候服务端返回的是一段可执行的 JavaScript代码。因为jsonp 跨域的原理就是用的动态加载 script的src ,所以我们只能把参数通过 url的方式传递, 所以jsonp的 type类型只能是get !

$.ajax({
    url: 'http://192.168.1.114/yii/demos/test.php', //不同的域
    type: 'GET', // jsonp模式只有GET 是合法的
    data: {        'action': 'aaron'
    },
    dataType: 'jsonp', // 数据类型
    jsonp: 'backfunc', // 指定回调函数名,与服务器端接收的一致,并回传回来})
其实jquery 内部会转化成
http://192.168.1.114/yii/demos/test.php?backfunc=jQuery2030038573939353227615_1402643146875&action=aaron然后动态加载
<script type="text/javascript"src="http://192.168.1.114/yii/demos/test.php?backfunc=>
然后后端就会执行backfunc(传递参数 ),把数据通过实参的形式发送出去。

在jquery 源码中, jsonp的实现方式是动态添加3f1c4e4b6b16bbbd69b2ee476dc4f83a标签来调用服务器提供的 js脚本。jquery 会在window对象中加载一个全局的函数,当 3f1c4e4b6b16bbbd69b2ee476dc4f83a代码插入时函数执行,执行完毕后就 3f1c4e4b6b16bbbd69b2ee476dc4f83a会被移除。同时jquery还对非跨域的请求进行了优化,如果这个请求是在同一个域名下那么他就会像正常的 Ajax请求一样工作。

24. http协议属于七层协议中的哪一层,下一层是什么

七层结构:物理层、数据链路层、网络层、传输层、会话层、表示层、应用层
tcp属于传输层;http属于应用层。
表现层

25. js垃圾回收机制知道哪些,v8引擎使用的哪一种

js的两种回收机制

1 标记清除(mark and sweep)
2 引用计数(reference counting)

javascript and V8 engine

Benefits and disadvantages of garbage collection mechanism

Benefits: greatly simplify the memory management code of the program, reduce the burden on programmers, and reduce the impact of long-term operation memory leak problem.

Disadvantages: Automatic recycling means that programmers cannot control memory. There is no excuse for garbage collection in ECMAScript. We cannot force it to perform garbage collection, let alone interfere with memory management.

V8 automatic garbage collection algorithm
https://segmentfault.com/a/11...

26. When is the scope generated?

Page loading --> Create window global object and generate global scope --> Then generate execution context, pre-parse variables (variable promotion), and generate global variable objects;
$scope

27. What is the principle of long connection of websocket

Meaning

Websocket is a persistent protocol, compared with non-persistent protocols such as HTTP.

Principle

Similar to long round robin long connection; send a request; get information continuously

28. http缓存知道哪些

http://blog.csdn.net/yzf91321...

29. 讲一下事件循环机制

执行上下文(Execution context)
函数调用栈(call stack)
队列数据结构(queue)
Promise

https://zhuanlan.zhihu.com/p/...

30. 理解web安全吗?都有哪几种,介绍以及如何预防

1.XSS,也就是跨站脚本注入

攻击方法:1. 手动攻击:
编写注入脚本,比如”/><script>alert(document.cookie());</script><!--等,
手动测试目标网站上有的input, textarea等所有可能输入文本信息的区域
2. 自动攻击
利用工具扫描目标网站所有的网页并自动测试写好的注入脚本,比如:Burpsuite等
防御方法:
1. 将cookie等敏感信息设置为httponly,禁止Javascript通过document.cookie获得
2. 对所有的输入做严格的校验尤其是在服务器端,过滤掉任何不合法的输入,比如手机号必须是数字,通常可以采用正则表达式
3. 净化和过滤掉不必要的html标签,比如:<iframe>, alt,<script> 等
4. 净化和过滤掉不必要的Javascript的事件标签,比如:onclick, onfocus等
5. 转义单引号,双引号,尖括号等特殊字符,可以采用htmlencode编码 或者过滤掉这些特殊字符
6. 设置浏览器的安全设置来防范典型的XSS注入

2.SQL注入

攻击方法:
编写恶意字符串,比如‘ or  1=1--等,
手动测试目标网站上所有涉及数据库操作的地方
防御方法:1. 禁止目标网站利用动态拼接字符串的方式访问数据库2. 减少不必要的数据库抛出的错误信息3. 对数据库的操作赋予严格的权限控制4. 净化和过滤掉不必要的SQL保留字,比如:where, or, exec 等5. 转义单引号,上引号,尖括号等特殊字符,可以采用htmlencode编码 或者过滤掉这些特殊字符

3.CSRF,也就是跨站请求伪造

就是攻击者冒用用户的名义,向目标站点发送请求
防范方法:1. 在客户端进行cookie的hashing,并在服务端进行hash认证2. 提交请求是需要填写验证码3. 使用One-Time Tokens为不同的表单创建不同的伪随机值

40. sessionStorage和localstorage能跨域拿到吗?比如我在www.baidu.com设置的值能在m.baidu.com能拿到吗?为什么

localStorage会跟cookie一样受到跨域的限制,会被document.domain影响

41. When does localstorage expire when it cannot be deleted manually?

Unless it is cleared, it will be saved permanently with clear().
sessionStorage is only valid in the current session, after closing the page or browser Cleared

42. What domains can cookies be set to? Can .com be set?

It can be achieved by setting domin

43. Do you think the login status can be saved in sessionstorage or localstorage or cookies or whichever method you know? Where is it stored? ? ? Why is it saved there

44. flux -> redux -> mobx What is the essence of the change

Storage structure will process objects observable functional style vs object-oriented
https:/ /zhuanlan.zhihu.com/p/...

45. How to load the corresponding chunk file for on-demand routing? In other words, how does the browser know when to load this chunk, and how does webpack identify the multiple hashed chunk files

50. What is the difference between get and post? Can get pass data through the body?

To put the data into the body, it must be retrieved through POST, which is restricted by the HTTP protocol.

51. 下拉刷新你怎么实现

52. 预加载options请求为什么会出现,能避免这个请求吗?

2018年面试题总结

收集一下网上的2018年的面试题 ; 希望能对你有所帮助~~

1.使用css实现一个持续的动画效果

animation:mymove 5s infinite;
@keyframes mymove {
from {top:0px;}
to {top:200px;}
}animation-name    规定需要绑定到选择器的 keyframe 名称。animation-duration    规定完成动画所花费的时间,以秒或毫秒计。animation-timing-function    规定动画的速度曲线。animation-delay    规定在动画开始之前的延迟。animation-iteration-count    规定动画应该播放的次数。animation-direction    规定是否应该轮流反向播放动画。

2.使用js实现一个持续的动画效果

最开始的思路是用定时器实现,最后没有想的太完整,面试官给出的答案是用requestAnimationFrame

· 定时器思路var e = document.getElementById(&#39;e&#39;)var falg = true;var left = 0;
setInterval(() => {
    left == 0 ? falg = true : left == 100 ? falg = false : &#39;&#39;
    falg ? e.style.left = ` ${left++}px` : e.style.left = ` ${left--}px`}, 1000 / 60)
· requestAnimationFrame
兼容性处理window.requestAnimFrame = (function(){  return  window.requestAnimationFrame       ||          window.webkitRequestAnimationFrame ||          window.mozRequestAnimationFrame    ||          function(callback){            window.setTimeout(callback, 1000 / 60);
          };
})();var e = document.getElementById("e")var flag = true;var left = 0;function render() {
    left == 0 ? flag = true : left == 100 ? flag = false : &#39;&#39;;
    flag ? e.style.left = ` ${left++}px` :
        e.style.left = ` ${left--}px`;
}
(function animloop() {
    render();
    requestAnimFrame(animloop);
})();

不足之处请指正(毕竟是现学的)顺便查了一下优势:

浏览器可以优化并行的动画动作,更合理的重新排列动作序列,并把能够合并的动作放在一个渲染周期内完成,从而呈现出更流畅的动画效果
解决毫秒的不精确性
避免过度渲染(渲染频率太高、tab 不可见暂停等等)
注:requestAnimFrame 和 定时器一样也头一个类似的清除方法 cancelAnimationFrame

3.右边宽度固定,左边自适应

第一种:<style>body{    display: flex;
}.left{    background-color: rebeccapurple;    height: 200px;    flex: 1;
}.right{    background-color: red;    height: 200px;    width: 100px;
}</style><body>
    <p class="left"></p>
    <p class="right"></p></body>第二种<style>
    p {        height: 200px;
    }    .left {        float: right;        width: 200px;        background-color: rebeccapurple;
    }    .right {        margin-right: 200px;        background-color: red;
    }</style><body>
    <p class="left"></p>
    <p class="right"></p></body>

4.水平垂直居中

第一种#container{    position:relative;
}#center{    width:100px;    height:100px;    position:absolute;    top:50%;    left:50%;    transform: translate(-50%,-50%);
}
第二种#container{    position:relative;
}#center{    width:100px;    height:100px;    position:absolute;    top:50%;    left:50%;    margin:-50px 0 0 -50px;
}
第三种#container{    position:relative;
}#center{    position:absolute;    margin:auto;    top:0;    bottom:0;    left:0;    right:0;
}
第四种 flex#container{    display:flex;    justify-content:center;    align-items: center;
}

5.四种定位的区别

`static` 是默认值
`relative` 相对定位 相对于自身原有位置进行偏移,仍处于标准文档流中
`absolute` 绝对定位 相对于最近的已定位的祖先元素, 有已定位(指`position`不是`static`的元素)祖先元素, 以最近的祖先元素为参考标准。如果无已定位祖先元素, 以`body`元素为偏移参照基准, 完全脱离了标准文档流。
`fixed` 固定定位的元素会相对于视窗来定位,这意味着即便页面滚动,它还是会停留在相同的位置。一个固定定位元素不会保留它原本在页面应有的空隙。

6.封装一个函数,参数是定时器的时间,.then执行回调函数。

function sleep (time) {  return new Promise((resolve) => setTimeout(resolve, time));
}

7.一行代码实现数组去重?

[...new Set([1,2,3,1,&#39;a&#39;,1,&#39;a&#39;])]

8.使用addEventListener点击li弹出内容,并且动态添加li之后有效

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>var ulNode = document.getElementById("ul");
    ulNode.addEventListener(&#39;click&#39;, function (e) {        if (e.target && e.target.nodeName.toUpperCase() == "LI") {
            alert(e.target.innerHTML);
        }
    }, false);

9.怎么判断两个对象相等

JSON.stringify(obj)==JSON.stringify(obj);//true

10.Vue router 除了 router-link 怎么实现跳转?

router.go(1)router.push(&#39;/&#39;)

11.Vue router 跳转和 location.href 有什么区别?

router 是 hash 改变
location.href 是页面跳转,刷新页面

12. Rearrange and redraw

Part of the rendering tree (or the entire rendering tree) needs to be reanalyzed and the node size needs to be recalculated. This is called rearrangement. Note that there will be at least one reflow-initialization page layout.
Due to changes in the geometric properties of nodes or changes in style, such as changing the background color of elements, some content on the screen needs to be updated. Such updates are called repaints.

13. What situations will trigger reflow and redraw

Add, delete, and update DOM nodes
Hide a DOM node through display: none-trigger reflow and redraw
Hide a DOM node by visibility: hidden - only triggers redraw, because there are no geometric changes
Move or animate DOM nodes in the page
Add a style sheet and adjust the style attributes
User behavior, such as Resize the window, change the font size, or scroll.

14.js bind 实现机制?手写一个 bind 方法?

function bind(fn, context){  return function (){     return fn.apply(context, arguments);
  }
}// 柯理化函数思想   感谢pursuitTom的提出Function.prototype.bind = function (context) {    var args = Array.prototype.slice.call(arguments, 1);    var _this = this;    return function () {        var thisArgs = [].slice.call(arguments);        return _this.apply(context, args.concat(thisArgs))
    };
}// ES6写法 感谢waterc的提出Function.prototype.bind = function(context, ...res) {
    let self = this
    return function(...arg) {        return self.apply(context, [...res,...arg])
    }
}

15.多个函数

var a = (function(){return &#39;1&#39;;}, function(){return 1;})();console.log(typeof a); //number

16.__proto__、prototype、Object.getPrototypeOf()

__proto__是指内部原型,和Object.getPrototypeOf()结果等价function f(){}f.__proto__ === Object.getPrototypeOf(f); //truef.prototype === Object.getPrototypeOf(f); //false

17.浏览记录前后跳转(尚未试验)

<a href="javascript:history.go(-1)">backward</a><a href="javascript:history.go(1)">forward</a>

下面再有的题就不写序号了;正好到17;是自己喜欢的数字;哈哈

setTimeout 和 setInterval 细谈

常问的点,前者是在一定时间过后将函数添加至执行队列,执行时间=延迟时间+之前函数代码执行时间+执行函数时间。
后者是不管前一次是否执行完毕,每隔一定时间重复执行,用于精准执行互相没有影响的重复操作。
如果需要控制前后执行顺序,最好使用setTimeout模拟setInterval

var time = 400, times = 0, max = 10;
function func(){
  times++;  if(times < max){    //code here
    setTimeout(func, time);
  } else {
    console.log("finished");
  }
}
setTimeout(func, time);

判断多图片加载完毕

注:用jQueryObject.ready()只能判断dom结构加载完毕
好像描述的不是很清楚,这里写一下代码。
方法1:

var counter = 0;var queryInterval = 30; //msvar pics = document.getElementsByClassName("pics");function singleQuery(i){  if(pics[i].complete){
    counter++;    console.log(i + " is loaded");
  } else {
    setTimeout(singleQuery, queryInterval, i);
  }
}function allQuery(callback){  if(counter < pics.length){    console.log("current number of loaded pics: " + counter);
    setTimeout(allQuery, queryInterval, callback);
  } else {    console.log("All pics are loaded.");
    callback();
  }
}for(var i = 0; i < pics.length; i++){
  setTimeout(singleQuery, queryInterval, i);
}

setTimeout(allQuery, queryInterval, callback);

主要也是采用setTimeout模拟轮询,判断方式是img标签dom的complete属性(布尔值),缺点是定时器太多。

方法2:

var counter = 0, queryInterval = 50;var pics = document.getElementsByClassName("pics");for(var i = 0; i < pics.length; i++){
  pics[i].onload = function(){
    counter++;    console.log(this.id + " is loaded");
  }
}function queryPictures(callback){  if(counter < pics.length){    console.log("current number of loaded pics: " + counter);
    setTimeout(queryPictures, queryInterval, callback);
  } else {    console.log("All pics are loaded");
    callback();
  }
}

setTimeout(queryPictures, queryInterval, callback);

利用onload绑定图片加载成功后的回调,通过计数器判断是否加载完毕。

CSS margin重叠问题

块元素在垂直方向上的margin是很奇怪的,会有重叠现象。
如果display都是block,有三种情况:
外间距均为正数,竖直方向上会选择最大的外边距作为间隔
一正一负,间距 = 正 - |负|
两个负,间距 = 0 - 绝对值最大的那个
设置display: inline-block的盒子不会有margin重叠,position: absolute的也不会出现。

CSS选择器优先级 && CSS选择器效率

ID > 类 > 标签 > 相邻 > 子选择器 > 后代选择器 > * > 属性 > 伪类

object.propertyIsEnumerable(xxx)

判断对象中是否有xxx属性,并且能通过for in枚举,如Array对象的length是不可枚举的

判断数组

function isArray(arr){    return Object.prototype.toString.call(arr) === &#39;[Object Array]&#39;;
}

git fetch && git pull

git pull自动完成了fetch最新远程版本,并且和本地进行merge
git fetch获得远程分支,要继续手动merge合并

WebSocket

HTML5带来的新协议,通过类似HTTP的请求建立连接。主要目的是可以获取服务端的推送。
原来的方式可能是使用long poll(即不中断连接一直等待数据),或者是ajax轮询的方式(每隔一段时间发送请求,建立连接,询问是否有新的数据)。这两种方式的缺点在于long poll的阻塞,以及ajax轮询的冗余连接。
WebSocket的设计思想有点类似于回调,在发送请求升级服务端的协议并收到确认信息后,服务端一有新的信息/数据就会主动推送给客户端,至于要一次HTTP握手便可以建立持久连接

跨域相关

只要协议、域名、端口有不同,则视为不同的域。(域名和域名对应的IP也是跨域)

1.CORS: Cross-Origin Resource Sharing

基于服务器支持的跨域,服务器设置Access-Control-Allow-Origin响应头,浏览器可允许跨域

2.设置domain

能从子域设到主域,如a.b.c.com—>b.c.com—>c.com
具体情况:在页面中用iframe打开了另一个页面(前提:两个页面主域是相同的)
利用frameElement.contentWindow.document.domain设置frame子页面的主域,document.domain设置主页面的主域,之后就能互相获取dom中的数据。
缺点是只能用于不同子域间的交互。

3.例如拥有src属性的img标签,每次改变src属性,都会发起http请求。

var img = new Image();
img.onload = function(){  //code here};
img.onerror = function(){  //code here};
img.src="http://server.com/data?query=3";

缺点是只能使用GET请求,不能获取数据,一般用于提交统计信息什么的。
script、link、iframe只有在添加到DOM中才会发起请求

4.HTML5 postMessage

支持IE8+和主流浏览器,写法也简单..

//source: http://test.org:4000//get the window object of target originvar win = window.open("http://target.com");//or this, when a frame is usedvar win = document.getElementById("targetId").contentWindow;
win.postMessage("data here", "http://target.com/rest");//target: http://target.com/tinyfunction handleMessage(event){  if(event.orgin!="http://test.org:4000")    return;  var data = event.data;  //code here

  //event.source is window.opener
  event.source.postMessage("response data here", event.origin);
}
window.addEventListener("message", handleMessage, false);

5.window.name

即使在页面打开多层iframe后,每个iframe中window.name 属性值都是相同的,以此用作数据传输的工具。
但由于跨域的限制,是无法获取另一个frame中的window.name数据,所以要使用一个同域的代理(proxy.html):

6. jsonp

目前主流跨域方法
调用其他域的脚本获取数据,前提是另一个域能知道回调函数名,这个可以通过请求发送给目标域。
直接写jQuery封的jsonp

$.getJSON("http://target.com/data?callback=callbackFunctionName", function(data){});

$.getJSON会把获取的responseText转为json,如果url中有callback参数,数据会以script标签形式获取。

针对上方问题存在没有解答的 ; 或则解答不正确详细的 ; 欢迎留言 ; 我会及时更正 ; 也欢迎留下你认为经典的面试题 ; 我都会补充进来 ; 共同进步

相关学习推荐:javascript视频教程

The above is the detailed content of Sharing of JS interview question records in 2017 and 2018. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Detailed explanation of the steps to directly implement the like function with AjaxNext article:Detailed explanation of the steps to directly implement the like function with Ajax

Related articles

See more