Skip to content

自问自答 #9

@luke93h

Description

@luke93h

HTML5新增了哪些内容或API

  • 新增api:Geolocation、Canvas/WebGL、webWorker、Audio/Video等等
  • 新增标签:HTML 5提供了一些新的元素和属性,反映典型的现代用法网站。其中有些是技术上类似
    标签,但有一定含义,例如(网站导航块)和``和

input和textarea的区别

  • input: 单行输入,值为value
  • textarea: 多行输入,值为children

flex布局-弹性布局

  • 容器的属性
  1. flex-direction: row | row-reverse | column | column-reverse,主轴方向
  2. flex-wrap: nowrap | wrap | wrap-reverse,换行方式
  3. flex-flow: ||
  4. justify-content: flex-start | flex-end | center | sapce-between | space-around
  5. align-items: flex-start | flex-end | center | baseline | stretch
  6. align-content: flex-start | flex-end | center | space-between | space-around | stretch
  • 项目属性
  1. order:
  2. flex-grow: /* default 0 */
  3. flex-shrink: /* default 1 */
  4. flex-basis: | auto /* default auto */
  5. flex: flex-grow, flex-shrink 和 flex-basis的缩写
  6. align-self: auto | flex-start | flex-end | center | baseline | stretch

css相关实现

  1. 左边定宽、右边自适应

  2. BFC

es相关

  1. 数组方法
  • 创建方法:
var arr1 = [1, 2, 3, 4, 5];
var arr2 = new Array(1, 2, 3, 4, 5)
  1. 增、删方法
  • push,pop,shift,unshift,splice
arr.splice(start, deleteCount, value)

var a = [1,2,3]
a.splice(1,1,222) // a为[1, 222, 3],返回[2]
a.splice(1,2,333) // a为[1, 333],返回[222,3]
  1. 其他
  • sort: 默认字典序;小于0--第一个参数在前,等于0-无所谓,大于0--第一个参数在后
  • slice:[start, end), 返回新数组
  • forEach,map,every,some
  • filter
  • reduce, reduceRight

正则

  1. 字符类
正则 含义
[...] 方括号内的任意字符
[^...] 不在方括号内的任意字符
. 除换行符和终止符外的任意字符
\w [a-zA-Z0-9]
\W [^a-zA-Z0-9]
\s 空白符
\S 非空白符
\d [0-9]
\D [^0-9]
  1. 重复
正则 含义
{n, m} 至少n次,最多m次
{n,} 至少n次
{n} n次
? 0次或者1次
+ {1,}
* {0,}

非贪婪匹配: ?? +? *?,会尽可能少的匹配

  1. 选择、引用、分组

| () \1 \2 \3 ......
(?....): 只组合,不记忆

  1. 匹配位置
正则 含义
^ 开头
$ 结尾
\b 单词边界
\B 非单词边界
(?=p) 零宽正向先行断言
(?!p) 零宽负向先行断言
  1. 修饰符
正则 含义
i 不区分大小写
g 全局匹配
m 多行匹配
  1. String方法
  • search
  • replace
  • match
  • split
  1. 正则方法
  • exec
  • test

cookie、localStorage、sessionStorage

  1. localStorage、sessionStorage

用法:

var name = localStorage.name
loacalStorage.name = 'luke'

setItem、getItem、removeItem

不同处 localStorage sessionStorage
有效期 永久 会话期间
作用域 文档源 文档源+同一个窗口

文档源 = 协议名 + 主机名(例:https + www.baidu.com)

  1. onstaorage事件
    key newValue oldValue storageArea url

  2. cookie

有效期: 默认直到浏览器关闭 , expirationtime、max-age

作用域:默认-协议 + 主机名 + 路径, domain、path可修改

类型化数组和ArrayBuffer

常用dom方法

  1. 获取dom

    • getElementById
    • getElementsByName
    • getElementsByTagName
    • getElementsByClassName
    • querySelectorAll
    • querySelector
  2. Node属性

    • parentNode 父节点

    • childNodes 只读,类数组,实时子节点

    • firstChild、lastChild 第一个、最后一个子节点

    • nextSibling、previoursSibling 下一个、前一个兄弟节点

    • nodeType 9-Document、1-Element、3-Text、8-Commnet、11-DocumentFragment

    • nodeValue 节点的文本内容或注释内容

    • nodeName 元素的标签名

    • firstElementChild、lastElementChild

    • nextElementSibling、previoursElementSibling

    • children

    • childElementCount

  3. 设置和获取html属性

    • getAttribute
    • setAttribute
    • hasAttribute
    • removeAttribute
    • dataset
    • attributes
    • innerHTML
    • textContent
    • nodeValue
  4. 操作dom

    • appendChild、insertBefore
    • removeChild
  5. 坐标信息

    • document.documentElement.pageXOffset、document.documentElement.pageYOffset 滚动条位置
    • getBoundingClinetRect() , 返回left、top、right、bottom等属性,相对于视口
  6. 选中文本的内容

    • window.getSelection().toString()
    • document.selection.createRange().text

React中 PureComponent 和 Component的区别

  • PureComponent:如果props和state没有发生改变,则shouldComponent返回false

  • Component: shouldComponent默认返回true

源码如下

function PureComponent(props, context, updater) {
  ....
}
pureComponentPrototype.isPureReactComponent = true;

function checkShouldComponentUpdate(
  workInProgress,
  oldProps,
  newProps,
  oldState,
  newState,
  newContext,
) {
  // 组件实例
  const instance = workInProgress.stateNode;
  // 组件构造函数
  const ctor = workInProgress.type;

  // 用户定义的shouldComponentUpdate
  if (typeof instance.shouldComponentUpdate === 'function') {
    const shouldUpdate = instance.shouldComponentUpdate(
      newProps,
      newState,
      newContext,
    );

    return shouldUpdate;
  }

  // PureComponent会返回浅比较的结果
  if (ctor.prototype && ctor.prototype.isPureReactComponent) {
    return (
      !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)
    );
  }

  // Component默认返回true
  return true;
}

Explain event delegation 事件委派

事件传播分为三个阶段

  1. 捕获阶段
  2. 发生事件的dom被触发
  3. 冒泡阶段

this

  1. fn.bind(o,args...)
  2. fn.call(o,args...)
  3. fn.apply(0,[...args])
  4. () => {}
  5. new Fn()
  6. obj.fn()
  7. fn() // 指向window

prototype

F = F.prototype.constructor

Explain why the following doesn't work as an IIFE: function foo(){ }()

浏览器在执行js前 ,会先编译js文件;访问到此处,遇到function关键字,默认为函数声明,会将声明提前,导致执行失败;正确的使用方法是(function foo(){ })()

typeof

类型 结果
Null 'object'
Object 'object'
Array 'object'
RegExp 'object'
Date 'object'
Undefined 'undefined'
Boolean 'boolean'
Number 'number'
String 'string'
Symbol 'symbol'
Function 'function'

JS怎样判断一个对象是否存在"环"?

当要转化的对象有“环”存在时(子节点属性赋值了父节点的引用),为了避免死循环,JSON.stringify 会抛出异常

function cycleDetector(obj) {
  if(!isPlainObject(obj)){
    console.log("obj须为纯对象");
    return;
  }
  let hasCircle = false,
    cache = [];
  cycle(obj)
  return hasCircle;
  function isPlainObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]';
  };
  function cycle(obj) {
    if(cache.indexOf(obj) != -1) {
      hasCircle = true;
      return;
    };
    cache.push(obj);
    Object.keys(obj).forEach(key => {
      const value = obj[key];
      if (isPlainObject(value)) {
        cycle(value);
      }
    })
    cache.pop();
  };
};

闭包

定义:函数体内部的变量都可以保存在函数作用域内

变量作用域在函数定义时决定,而不是执行时决定。

函数式编程

尽量使用函数来处理逻辑

高阶函数

操作函数的函数

不完全函数

把一次完整的函数调用拆分成多次函数调用

记忆

一种编程技巧,牺牲算法的空间复杂度以换取更优的时间复杂度,在客户端js中代码的执行时间复杂度往往成为瓶颈,因此十分推荐。

一般利用闭包实现缓存功能。

匿名函数的用处

  1. 传给高阶函数
  2. IIFE
  3. 赋值给变量,对象属性

本地对象,宿主对象,内置对象

  1. Native Object:Object,Function,Array,Date

  2. host object: bom, dom

  3. buid-in Object: Math

call & apply

let obj = {
  a: 1
}
function add(b, c){
  this.a = this.a + b + c
}
add.call(obj, 1, 2) // obj.a = 4
add.apply(obj, [1, 2]) // obj.a = 7

feature detection、feature inference、UA string

  1. feature detection
if( typeof Object.keys === 'function'){
  let keys = Object.keys(obj)
}
  1. feature inference
if (document.getElementsByTagName) {
  element = document.getElementById(id);
}
  1. UA string
if (navigator.userAgent.indexOf("MSIE 7") > -1){
    //do something
}

Ajax

function get(url, cb) {
  var req = new XMLHttpRequest()
  req.open('GET', url)
  req.onreadystatechange = function() {
    if(request.readyState === 4 $$ request.satatus === 200){
      var type = request.getResponseHeader('Content-Type')
      if(type === 'application/json'){
        cb(JSON.parse(request.responseText))
      }else{
        cb(request.responseText)
      }
    }
  }
  req.send(null)
}

JSONP

预先定义函数,在引入的跨域脚本中调用该函数。

类型转换

转化为字符串 数字 布尔值 对象
undefineed 'undefined' NaN false throwsTypeError
null 'null' 0 false throwsErrow
true 'true' 1 new Boolean(true)
false 'false' 0 new Boolead(false)
'' 0 false new String('')
'1.2' 1.2 true new String('1.2')
'one' NaN true new String('one')
0 '0' false new Number(0)
-0 '0' false new Number(0)
Infinity 'Infinity' true new Number(Infinity)
-Infinity '-Infinity' true new Number(-Infinity)
1 '1' true new Number(1)

Difference between window load event and document DOMContentLoaded event

  1. window load: 整个页面j加载完毕,包括图片,css,scripts
  2. document load: dom可以使用,优先于图片和其他内容

三元操作符

  1. 三元是指三个操作数
getting = "hello" + (username ? username : "there")

单页应用

单页Web应用(single page web application,SPA),就是只有一张Web页面的应用,是加载单个HTML 页面并在用户与应用程序交互时动态更新该页面的Web应用程序。

优点:

  1. 分离前后端关注点,前端负责界面显示,后端负责数据存储和计算,各司其职,不会把前后端的逻辑混杂在一起;
  2. 减轻服务器压力,服务器只用出数据就可以,不用管展示逻辑和页面合成,吞吐能力会提高几倍
  3. 开发效率极高,速度快,质量高,产量多。
    缺点:
  4. SEO问题,现在可以通过Prerender等技术解决一部分;

mutable and immutable objects

如果一个对象它被构造后其,状态不能改变,则这个对象被认为是不可变的(immutable )。

箭头函数

绑定this

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions