【3】「2021」前端总结之JavaScript篇(一)

154 阅读8分钟

一、数据类型

字符串(String)、数字(Number)、布尔(Boolean)、对空(null)、未定义(undefined)、Symbol、对象(Object)、BigInt。

其中 Symbol 和 BigInt 是ES6 中新增的数据类型:

  • Symbol 代表创建后独一无二且不可变的数据类型,它主要是为了解决可能出现的全局变量冲突的问题。
  • BigInt 是一种数字类型的数据,它可以表示任意精度格式的整数,使用 BigInt 可以安全地存储和操作大整数,即使这个数已经超出了 Number 能够表示的安全整数范围。

二、ES5之数组方法使用

1、concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

const array1 = ['a', 'b', 'c']; 
const array2 = ['d', 'e', 'f']; 
console.log(array1.concat(array2)); // expected output: Array ["a", "b", "c", "d", "e", "f"]

2、 every() 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。(注意:若收到一个空数组,此方法在一切情况下都会返回 true。)

const isBelowThreshold = (currentValue) => currentValue < 40; 
const array1 = [1, 30, 39, 29, 10, 13]; 
console.log(array1.every(isBelowThreshold)); // expected output: true

3、fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。

const array1 = [1, 2, 3, 4];// fill with 0 from position 2 until position 4 
console.log(array1.fill(0, 2, 4));// expected output: [1, 2, 0, 0] // fill with 5 from position 1 
console.log(array1.fill(5, 1)); // expected output: [1, 5, 5, 5] 
console.log(array1.fill(6)); // expected output: [6, 6, 6, 6]

4、filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。 

const words = ['spray', 'elite', 'exuberant', 'destruction', 'present']; 
const result = words.filter(word => word.length > 6); 
console.log(result); // expected output: Array ["exuberant", "destruction", "present"] 
let arr1 = [{id:1,name:'zhangsan'},{id:2,name:'lisi'}]; 
let arr2 = arr1.filter((item,index,arr)=>{ return item.id === 1 }) 
console.log(arr2); //[{id:1,name:'zhangsan'}]

5、find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

const array1 = [5, 12, 8, 130, 44]; 
const found = array1.find(element => element > 10); 
console.log(found); // expected output: 12

6、findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。

const array1 = [5, 12, 8, 130, 44]; 
const isLargeNumber = (element) => element > 13; 
console.log(array1.findIndex(isLargeNumber)); // expected output: 3

7、forEach() 方法对数组的每个元素执行一次提供的函数。

const array1 = ['a', 'b', 'c']; 
array1.forEach(element => console.log(element)); 
// expected output: "a" 
// expected output: "b" 
// expected output: "c"

8、indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; 
console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 
console.log(beasts.indexOf('bison', 2)); // expected output: 4 
console.log(beasts.indexOf('giraffe')); // expected output: -1

9、includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

const array1 = [1, 2, 3]; 
console.log(array1.includes(2)); // expected output: true 
const pets = ['cat', 'dog', 'bat']; 
console.log(pets.includes('cat')); // expected output: true 
console.log(pets.includes('at')); // expected output: false

10、join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。

const elements = ['Fire', 'Air', 'Water']; 
console.log(elements.join()); // expected output: "Fire,Air,Water" 
console.log(elements.join('')); // expected output: "FireAirWater" 
console.log(elements.join('-')); // expected output: "Fire-Air-Water"

11、lastIndexOf() 方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']; 
console.log(animals.lastIndexOf('Dodo')); // expected output: 3 
console.log(animals.lastIndexOf('Tiger')); // expected output: 1

12、map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。

const array1 = [1, 4, 9, 16]; // pass a function to map 
const map1 = array1.map(x => x * 2); 
console.log(map1); // expected output: Array [2, 8, 18, 32]

13、pop()方法从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']; 
console.log(plants.pop()); // expected output: "tomato" 
console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"] plants.pop(); 
console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage"]

14、push() 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度。

const animals = ['pigs', 'goats'];
const count = animals.push('cows'); 
console.log(count); // expected output: 3 
console.log(animals); // expected output: Array ["pigs", "goats", "cows"] animals.push('chickens'); 
console.log(animals); // expected output: Array ["pigs", "goats", "cows", "chickens"] 
const person = []; 
person.push({ name:"Colin", age:"18" }) 
console.log(person);

15、reverse() 方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。

const array1 = ['one', 'two', 'three']; 
console.log('array1:', array1); // expected output: "array1:" Array ["one", "two", "three"] 
const reversed = array1.reverse(); 
console.log('reversed:', reversed); // expected output: "reversed:" Array ["three", "two", "one"] 
/* Careful: reverse is destructive. It also changes the original array */ 
console.log('array1:', array1); // expected output: "array1:" Array ["three", "two", "one"]

16、shift() 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

const array1 = [1, 2, 3]; 
const firstElement = array1.shift(); 
console.log(array1); // expected output: Array [2, 3] 
console.log(firstElement); // expected output: 1

17、unshift() 方法将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组)。

const array1 = [1, 2, 3]; 
console.log(array1.unshift(4, 5)); // expected output: 5 
console.log(array1); // expected output: Array [4, 5, 1, 2, 3]

18、slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; 
console.log(animals.slice(2)); // expected output: Array ["camel", "duck", "elephant"] 
console.log(animals.slice(2, 4)); // expected output: Array ["camel", "duck"] 
console.log(animals.slice(1, 5)); // expected output: Array ["bison", "camel", "duck", "elephant"]

19、splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb'); // inserts at index 1 
console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "June"] 
months.splice(4, 1, 'May'); // replaces 1 element at index 4 
console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "May"]

20、some() 方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。注意:如果用一个空数组进行测试,在任何情况下它返回的都是false。

const array = [1, 2, 3, 4, 5]; // checks whether an element is even 
const even = (element) => element % 2 === 0; 
console.log(array.some(even)); // expected output: true

21、sort() 方法用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的

由于它取决于具体实现,因此无法保证排序的时间和空间复杂性。

const months = ['March', 'Jan', 'Feb', 'Dec']; 
months.sort(); console.log(months); // expected output: Array ["Dec", "Feb", "Jan", "March"] 
const array1 = [1, 30, 4, 21, 100000]; 
array1.sort(); 
console.log(array1); // expected output: Array [1, 100000, 21, 30, 4]

22、toLocaleString() 返回一个字符串表示数组中的元素。数组中的元素将使用各自的 toLocaleString 方法转成字符串,这些字符串将使用一个特定语言环境的字符串(例如一个逗号 ",")隔开。

const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')]; 
const localeString = array1.toLocaleString('en', {timeZone: "UTC"}); 
console.log(localeString); // expected output: "1,a,12/21/1997, 2:12:00 PM", 
// This assumes "en" locale and UTC timezone - your results may vary

23、toString() 返回一个字符串,表示指定的数组及其元素。

const array1 = [1, 2, 'a', '1a']; 
console.log(array1.toString()); // expected output: "1,2,a,1a"

24、values() 方法返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值

const array1 = ['a', 'b', 'c']; 
const iterator = array1.values(); 
for (const value of iterator) { console.log(value); } 
// expected output: "a" // expected output: "b" // expected output: "c"

三、常用正则表达式大全

匹配身份证:d{15}|d{18}  
//身份证号(18位)正则 
var cP = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/; 
匹配国内电话号码:d{3}-d{8}|d{4}-d{7}    
评注:匹配形式如 0511-4405222021-87888822  
手机号码:^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])d{8}$ 
最小两个字符的名字:^[A-Za-z0-9\s\u4E00-\u9FA5]{2,15}$; 
匹配金额(0~99999,最多保留小数点后2位): 
let res = /^(0|([1-9][0-9]{1,4})|([1-9][0-9]{1,4})(\.\d{1,2}))$/;

四、ES5之JSON

1、JSON.stringify() 方法将一个 JavaScript 值(对象或者数组)转换为一个 JSON 字符串,如果指定了 replacer 是一个函数,则可以选择性地替换值,或者如果指定了 replacer 是一个数组,则可选择性地仅包含数组指定的属性。

JSON.stringify(value[, replacer [, space]]) JSON.stringify({}); // '{}' 
JSON.stringify(true); // 'true' 
JSON.stringify("foo"); // '"foo"' 
JSON.stringify([1, "false", false]); // '[1,"false",false]' 
JSON.stringify({ x: 5 }); // '{"x":5}' 
JSON.stringify({x: 5, y: 6}); // "{"x":5,"y":6}"

2、JSON.parse() 方法用来解析JSON字符串,构造由字符串描述的JavaScript值或对象。提供可选的 reviver 函数用以在返回之前对所得到的对象执行变换(操作)。

var json = '{"result":true, "count":42}'; 
obj = JSON.parse(json); 
console.log(obj.count); // expected output: 42 
console.log(obj.result); // expected output: true

五、ES5之语法和函数

1、undefined和null

null == undefined //true null === undefined //false

undefined 是没设值

null则是设定了为null值

2、typeof和instanceof

1)、typeof 用来获得 实例类型 :

typeof("123"); //string

2)、instanceof 判断变量是否为某类的实例

var a = [4,5]; alert(a instanceof Array); //true

3、调用函数的三种方式

1)、直接调用

windows.alert(); //or alert();

2)、call()调用(作用:动态地传入一个函数引用)

function Product(name, price) { this.name = name; this.price = price; } function Food(name, price) { Product.call(this, name, price); this.category = 'food'; } console.log(new Food('cheese', 5).name); // expected output: "cheese"

3)、apply()调用

apply和()call()基本相似,区别如下:

  • 通过call()调用函数时,括号必须详细列出每个参数
  • 通过apply()动态地调用函数时,可以在括号中以arguments来代表所有参数
  • 注意:call()方法的作用和 apply() 方法类似,区别就是call()方法接受的是参数列表,而apply()方法接受的是一个参数数组。
const numbers = [5, 6, 2, 3, 7]; 
const max = Math.max.apply(null, numbers); 
console.log(max); // expected output: 7 
const min = Math.min.apply(null, numbers); 
console.log(min); // expected output: 2 
/* 代码对比: 用简单循环完成 */ 
max = -Infinity, min = +Infinity; 
for (var i = 0; i < numbers.length; i++) { if (numbers[i] > max) max = numbers[i]; 
if (numbers[i] < min) min = numbers[i]; }

4、bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

this.x = 9; // 在浏览器中,this 指向全局的 "window" 对象 
var module = { x: 81, getX: function() { return this.x; } }; 
module.getX(); // 81 
var retrieveX = module.getX; retrieveX(); 
// 返回 9 - 因为函数是在全局作用域中调用的 
// 创建一个新函数,把 'this' 绑定到 module 对象 
// 新手可能会将全局变量 x 与 module 的属性 x 混淆 
var boundGetX = retrieveX.bind(module); 
boundGetX(); // 81

六、闭包

函数与对其状态即词法环境(lexical environment)的引用共同构成闭包(closure)。也就是说,闭包可以让你从内部函数访问外部函数作用域。在JavaScript,函数在每次创建时生成闭包。

function init() { 
    var name = "Mozilla"; 
    // name 是一个被 init 创建的局部变量 
    function displayName() { 
        // displayName() 是内部函数,一个闭包 alert(name); 
        // 使用了父函数中声明的变量 
    } 
    displayName(); 
} 
init(); /*弹出"Mozilla"*/

七、ES5之原型和原型链

JavaScript 只有一种结构:对象。每个实例对象( object )都有一个私有属性(称之为 proto )指向它的构造函数的原型对象(prototype )。该原型对象也有一个自己的原型对象( proto ) ,层层向上直到一个对象的原型对象为 null。根据定义,null 没有原型,并作为这个原型链中的最后一个环节。

1、继承属性

JavaScript 对象是动态的属性“包”(指其自己的属性)。JavaScript 对象有一个指向一个原型对象的链。当试图访问一个对象的属性时,它不仅仅在该对象上搜寻,还会搜寻该对象的原型,以及该对象的原型的原型,依次层层向上搜索,直到找到一个名字匹配的属性或到达原型链的末尾。

2、继承方法

JavaScript 并没有其他基于类的语言所定义的“方法”。在 JavaScript 里,任何函数都可以添加到对象上作为对象的属性。函数的继承与其他的属性继承没有差别,包括上面的“属性遮蔽”(这种情况相当于其他语言的方法重写)。

当继承的函数被调用时,this 指向的是当前继承的对象,而不是继承的函数所在的原型对象。

链接:juejin.im/post/58f94c…

developer.mozilla.org/zh-CN/docs/…

八、ES5之Date

1、创建 Date 对象的语法:

var myDate=new Date()

2、Date 对象方法

getDate() //从 Date 对象返回一个月中的某一天 (1 ~ 31)。 
getDay() //从 Date 对象返回一周中的某一天 (0 ~ 6)。 
getMonth() //从 Date 对象返回月份 (0 ~ 11)。 
getFullYear() //从 Date 对象以四位数字返回年份。 
getHours() //返回 Date 对象的小时 (0 ~ 23)。 
getMinutes() //返回 Date 对象的分钟 (0 ~ 59)。 
getSeconds() //返回 Date 对象的秒数 (0 ~ 59)。 
getMilliseconds() //返回 Date 对象的毫秒(0 ~ 999)。 
setDate() //设置 Date 对象中月的某一天 (1 ~ 31)。

developer.mozilla.org/zh-CN/docs/…