目录
最近接到一个偏前端的面试通知,作为一个老司机,突然发现无从下手,前端不就是HTML + CSS + JS三件套嘛,好像什么都挺清楚的,但是深入一想,好像知识体系还是非常模糊的,这里特地整理下材料,希望对大家有帮助。
当然我在海外,不知道适应国内的情况不。
一、基础知识
第一步,三件套大保健(HTML + CSS + JS)的基础知识需要过一遍,最好嘛从头看一遍,找找自己哪些地方不是很清晰的,其实即便你做了很久的前端,很多基础非常有可能依旧不是很清楚。
看W3C或者我找到一个网站有知识的整理,还不错:http://www.runoob.com/html/html-tutorial.html
以下是我找到的一些问题,复习完基础之后,可以试试。
Javascript
JS是前端唯一的,可以在面试中挖掘你水平的语言,所以需要非常深入的了解。以下几个知识点可以用于自我检测:
- Execution context, especially lexical scope and closures.
- Hoisting, function & block scoping and function expressions & declarations.
- Binding – specifically call, bind, apply and lexical this.
- Object prototypes, constructors and mixins.
- Composition and high order functions.
- Event delegation and bubbling.
- Type Coercion using typeof, instanceof and Object.prototype.toString.
- Handling asynchronous calls with callbacks, promises, await and async.
- When to use function declarations and expressions.
- What does the $ represent when using jQuery?
- Explain the this keyword and it’s behaviour in JS.
- What is the difference between the DOMContentLoaded and window.load events?
- This This This!!!!
- Prototype
DOM
这块其实概念很简单,但是很多时候我们用Jquery或者其他framework来处理,所以可能会非常不熟悉。
- Selecting or finding nodes using document.querySelector and in older browsers document.getElementsByClassName.
- Traversal up and down – Node.parentNode, Node.firstChild, Node.lastChild and Node.childNodes.
- Traversal left and right – Node.previousSibling and Node.nextSibling.
- Manipulation – add, remove, copy, and create nodes in the DOM tree. You should know operations such as how to change the text content of a node and toggle, remove or add a CSS classname.
- Performance – touching the DOM can be expensive when you have many nodes, you should at least know about document fragments and node caching.
CSS
- Layout – sitting elements next to each other and how to place elements in two columns vs three columns.
- Knowledge demonstration questions and quizzes (Explain the box model, create a tooltip plugin, describe the different values of CSS position)
- Responsive design – changing an element’s dimensions based on the browser width size.
- Adaptive design – changing an element’s dimensions based on specific break points.
- Specificity – how to calculate a selector’s specificity and how the cascade affects attributes.
- Appropriate namespacing and naming of classnames.
- What is the difference between display: block, display: inline and display: inline-block?
- Explain the box-model and how it affects various CSS properties.
- What is a normal HTTP request made up of?
- What is BEM and explain why using something like it could be useful in your CSS?
- position: relative, position: absolute and position: fixed
HTML
- Semantic markup.
- Tag attributes, such as disabled, async, defer and when to use data-*.
- Knowing how to declare your doctype (most people are not writing new pages every day and forget this) and what meta tags are available to use.
- Accessibility concerns, for example, making sure an input checkbox has a larger responding area (use label “for”). Also, role=”button”, role=”presentation”, etc.
二、提高篇
作为senior的工程师,光会大保健肯定不行,面试的时候还有cache,系统设计,proformance优化、算法等。在这里整理下相关知识:
- Critical rendering path.
- Service workers.
- Image optimizations.
- Lazy loading and bundle splitting.
- General implications of HTTP/2 and server-push.
- When to prefetch and preload resources.
- Reduce browser reflows and when to promote an element to the GPU.
- Differences between the browser layout, compositing and painting.
- HTTP requests – GET and POST along with associated headers such as Cache-Control, ETag, Status Codes, and Transfer-Encoding.
- Meta questions – About source control, UI, HTTP & the web in general etc. See if the candidate knows a bit more beyond their specific topic of interest.
- REST vs RPC.
- Security – when to use JSONP, CORs, and iFrame policies.
- CSS Preprocessing
- Testing/Debug
- Building and Automation Tools
- Common cross browser issues and how to resolve them
- CSS and JS minifying
三、资料推荐
对于this弄不清楚的,可以读一读这个:
https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/README.md#you-dont-know-js-this–object-prototypes
JS基础梳理:这位朋友写的非常棒,搜“JavaScript学习总结”:https://segmentfault.com/u/trigkit4/articles?page=5
四、笔记
这块是我自己的笔记,只记录了自己认为需要回看的东西
HTML
- <base> 标签描述了基本的链接地址/链接目标,该标签作为HTML文档中所有的链接标签的默认链接
- Block-Level, it takes whole line, <h1>, <p>, <ul>, <table>, <div>
- inline, won’t change line, like <span>, <b>, <td>, <a>, <img>
- 只有在浏览器不支持脚本或者禁用脚本时,才会显示 <noscript> 元素中的内容
- XHTML 是以 XML 格式编写的严格更纯净的 HTML
- HTML5: Canvas, SVG, MathML, Drag&Drop, Location, Video, Audio, input type, datalist
- localStorage: 一直存在
- sessionStorage: 关闭就clean
- websocket
- SSE – Server-sent event
- <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
- <div class=”container”><div class=”row” ><div class=”col-xs-6 col-sm-3″>
- What is progressive rendering? – make page faster
- Semantic tags are self-explanatory, <img>
- CDN的版本控制:last-modified/etag控制,没变化返回304,另外cache的控制是由expire/cafche-control
CSS
- 多重样式优先级: 内联样式)Inline style > (内部样式)Internal style sheet >(外部样式)External style sheet > 浏览器默认样式
- Box Modal:
- inline element 不能设置高度,宽度。从而理解了inline-block
- 相对定位,相对于元素的正常位置来进行定位。元素在页面占据位置。可以使用 top right bottom left 移动元素位置。
- 绝对定位,相对于最近一级的 定位不是 static 的父元素来进行定位。元素在页面不占据位置。 可以使用 top right bottom left 移动元素位置。
- vendor-prefixed properties offered by the relevant rendering engines (-webkit for Chrome, Safari; -moz for Firefox, -o for Opera, -ms for Internet Explorer)
- How do browsers read CSS? – From right to left.
- pseudo-elements – list: first-child
- Difference between standard/ strict mode and quirks mode? – quirks mode in browser allows u to render page for as old browsers. This is for backward compatibility.
JavaScript
- document.getElementById(“demo”).innerHTML
- 局部变量会在函数运行以后被删除。全局变量会在页面关闭后被删除
- 如果您把值赋给尚未声明的变量,该变量将被自动作为全局变量声明。如: carname=”Volvo”;
- null和underfined:
- typeof undefined // undefined
- typeof null // object
- null === undefined // false
- null == undefined // true
- 5 种不同的数据类型:string, number, boolean, object, function
- 3 种对象类型:Object, Date, Array
- 2 个不包含任何值的数据类型:null, undefined
- use strict
- 不允许使用未声明的变量
- 不允许删除变量或对象
- 不允许删除函数
- 不允许变量重名
- 不允许对一个使用getter方法读取的属性进行赋值
- 变量名不能使用 “eval”, “arguments” 字符串
- 由于一些安全原因,在作用域 eval() 创建的变量不能被调用:
- 禁止this关键字指向全局对象。
- JavaScript处理常用的method
- typeof()
- Number(“3.2”)
- toString()
- indexOf()
- substr()
- charAt()
- push() // to last
- pop() // last one
- shift() // remove first one
- reverse()
- addEventListener(“click”,function(){});
- document.getElementById(“intro”);
- document.getElementsByClassName(“intro”);
- var myDate=new Date();
- Math.round()
- Math.random()
- setInterval(function(){alert(“Hello”)},3000);
- void: 该操作符指定要计算一个表达式但是不返回值。
- Hoisting: 是 JavaScript 默认将当前作用域提升到前面去的的行为。使用表达式定义函数时无法提升。
- arguments.length 属性返回函数调用过程接收到的参数个数:
function myFunction(a, b) { return arguments.length; }
- 当函数没有被自身的对象调用时, this 的值就会变成全局对象。
- JSON.parse() 方法将数据转换为 JavaScript 对象
- setTimeout/setInterval/匿名函数执行的时候,this默认指向window对象
- Jquery常用method
- attr()
- append()
- addClass()
- css()
- $(selector).load(URL,data,callback);
- $.get(URL,callback);
- $.post(URL,data,callback);
- React 大体包含下面这些概念:
- 组件
- JSX
- Virtual DOM
- Data Flow
- JavaScript 是面向对象的语言,但 JavaScript 不使用类。 JavaScript 基于 [prototype][1]
- apply、call 二者而言,作用完全一样,只是接受参数的方式不太一样。func.call(this, arg1, arg2);func.apply(this, [arg1, arg2])
- How would you organize your Javascript code?
- Break the code into logical units, keep them all in separate files
- Use a script to concatenate/minify the files into a single bundle which you will serve as part of your app
- Use JS namespaces to avoid cluttering up the global namespace
- How can you add a method to a class already defined? – prototype
- attribute vs property
- <input type=“checkbox” checked=true/>
- $(‘input’).prop(‘checked’); // returns true
- $(‘input’).attr(‘checked’); // returns “checked”
- If an element has a default value, the attribute shows the default value even if the value has changed.
<input type="text" name="username" value="user123"> $('input').prop('value', '456user'); $('input').prop('value'); // returns "456user" $('input').attr('value'); // returns "user123"
- Can you name two programming paradigms important for JavaScript app developers?
- Prototypal inheritance (also: prototypes, OLOO).
- Functional programming (also: closures, first class functions, lambdas).
- What do you think of AMD vs CommonJS?
- AMD is better for browser, hence, the name ‘Asynchronous’, as it loads each distinct module in async manner instead of loading in one large file. No extra steps are required to use AMD, it works out-of-the-box. In my opinion, as it is its in Asynchronous nature, it makes alot of async http requests and may not be as performant as described by other devs.
- While, CommonJS, is a standard, mostly used in servers and it loads modules synchronously, though extra step is required if you want your JS file size to be minified and compressed.
- How do you organize your code? – model pattern, create model with method
- What’s the difference between host objects and native objects?
- Native objects: Object (constructor), Date , Math , parseInt , eval , string methods like indexOf and replace , array methods, …
- Host objects (assuming browser environment): window , document , location , history , XMLHttpRequest , setTimeout , getElementsByTagName , querySelectorAll
- Describe event bubbling.
- Event Bubbling 即指某个事件不仅会触发当前元素,还会以嵌套顺序传递到父元素中。直观而言就是对于某个子元素的点击事件同样会被父元素的点击事件处理器捕获。避免 Event Bubbling 的方式可以使用event.stopPropagation() 或者 IE 9 以下使用event.cancelBubble。
- Ternary expression: a>b? c:d
- Promises:Promise 则是把类似的异步处理对象和处理规则进行规范化, 并按照采用统一的接口来编写
- Event Loop: 优化JS单线程问题,就是在程序中设置两个线程:一个负责程序本身的运行,称为”主线程”;另一个负责主线程与其他进程(主要是各种I/O操作)的通信,被称为”Event Loop线程”(可以译为”消息线程”)。
- How would you compare two objects in JavaScript? – JSON.stringify()
- a = (2, 3, 5); what is the value of a? – 5. The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
- Does JavaScript pass parameter by value or by reference? – Primitive type (string, number, etc.) are passed by value and objects are passed by reference.
- JS中提供了一个DocumentFragment的机制,相信大家对这个并不陌生,它可以提供一个缓冲的机制,将DOM节点先放到内存中,当节点都构造完成后,再将DocumentFragment对象添加到页面中,这时所有的节点都会一次渲染出来,这样就能减少浏览器很多的负担,明显的提高页面渲染速度
- How could you prevent a click on an anchor from going to the link? – preventDefault()
- Travel Nodes
- parentNode
- childNodes[nodenumber]
- firstChild
- lastChild
- nextSibling
- previousSibling
- .firstChild.nodeValue;
- message bus for applications, message queues is for users and applications
HTML5 – Server-sent event
var source=new EventSource("demo_sse.php"); source.onmessage=function(event) { document.getElementById("result").innerHTML+=event.data + "<br>"; };
HTML5 – Web Worker
var w; function startWorker() { if(typeof(Worker) !== "undefined") { if(typeof(w) == "undefined") { w = new Worker("demo_workers.js"); } w.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; }; } else { document.getElementById("result").innerHTML = "你的浏览器不支持 Web Workers..."; } } function stopWorker() { w.terminate(); w = undefined; }
HTML5 – WebStoarge
if (localStorage.clickcount) { localStorage.clickcount=Number(localStorage.clickcount)+1; } else { localStorage.clickcount=1; } document.getElementById("result").innerHTML=" 你已经点击了按钮 " + localStorage.clickcount + " 次 "; //保存数据 function save(){ var siteurl = document.getElementById("siteurl").value; var sitename = document.getElementById("sitename").value; localStorage.setItem(sitename, siteurl); alert("添加成功"); } //查找数据 function find(){ var search_site = document.getElementById("search_site").value; var sitename = localStorage.getItem(search_site); var find_result = document.getElementById("find_result"); find_result.innerHTML = search_site + "的网址是:" + sitename; } Use Strict下的this function f(){ return !this; } // 返回false,因为"this"指向全局对象,"!this"就是false function f(){ "use strict"; return !this; } // 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。
Jquery Load
$("button").click(function(){ $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){ if(statusTxt=="success") alert("外部内容加载成功!"); if(statusTxt=="error") alert("Error: "+xhr.status+": "+xhr.statusText); }); });
Jquery Post
$("button").click(function(){ $.post("/try/ajax/demo_test_post.php", { name:"菜鸟教程", url:"http://www.runoob.com" }, function(data,status){ alert("数据: \n" + data + "\n状态: " + status); }); });
Scope and hoisting
var a = 1; function b() { a = 10; return; function a() {} } b(); console.log(a);
Explanation:
- function declaration function a(){} is hoisted first and it behaves like var a = function () {};. Hence in local scope variable a is created.
- If you have two variables with same name (one in global another in local), local variable always get precedence over global variable.
- When you set a = 10;, you are setting the local variable a , not the global one. Hence, the value of global variable remain same and you get, 1 in the log. ref: js hoisting/scope
- Extra: If you didnt have a function named as “a”, you will see 10 in the log.
Append Class
var li = document.createElement("li"); var text = document.createTextNode('Only one Item'); li.appendChild(text);
遍历页面所有元素
var all = document.getElementsByTagName("*"); for (var i=0, max=all.length; i < max; i++) { console.log(all[i]); }
遍历子节点
var usernameEle = document.getElementById("center"); var childs = usernameEle.childNodes; for(var i = childs.length - 1; i >= 0; i--) { console.log(childs[i]); }
参考文章:
https://www.linkedin.com/pulse/preparing-front-end-web-development-interview-2017-david-shariff
https://ashleynolan.co.uk/blog/a-guide-to-front-end-interviews
mark