E6语法@

简介

E6笔记,涉及Es5
语法
let,const,var,class,function,export
关键词解析
let:区域性变量声明
const:不可变变量值声明,必须初始化
var:声明的变量在window上
class:声明一段逻辑清晰的语法糖结构
function:声明函数式变量
export:声明用于加载文件中抛出的变量声明
示例
let a=1;
-------------------
const a=1;
-------------------
var a=1;
-------------------
export {Button as but}  from 'button.js';
-------------------
function a(){

};
-------------------
class Interest{
	constructor(x,y){
	 this.x=x;
	 this.y=y;
	}
		MyInterest(){
			let arr=[];
			console.log("111${[..arr,this.x,this.y]}!");
		}
};
let GetInterest=new Interest(2,3);
console.log(GetInterest.MyInterest());//11123
includes(), startsWith(), endsWith(),String.raw(),repeat(),padStart(),padEnd(),matchAll(),replaceAll()
函数释义:
includes():返回布尔值,表示是否找到了参数字符串。
startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
String.raw():该方法返回一个斜杠都被转义(即斜杠前面再加一个斜杠)的字符串
repeat():repeat方法返回一个新字符串,表示将原字符串重复n次
padStart()padEnd()trimStart():消除字符串头部的空格
trimEnd():消除字符串尾部的空格
replaceAll() :替换所有指定内容
matchAll():正则表达式验证
at():方法接受一个整数作为参数,返回参数指定位置的字符,支持负索引(即倒数的位置)。
示例
String.raw`Hi\n${2+3}!`
// 实际返回 "Hi\\n5!",显示的是转义后的结果 "Hi\n5!"
-------------------------------
let s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false
-------------------------------------
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""

-------------------------------------
'x'.padStart(5, 'ab') // 'ababx'
'x'.padEnd(5, 'ab') // 'xabab'
'1'.padStart(10, '0') 
'09-12'.padStart(10, 'YYYY-MM-DD') 
-----------------------------------------
const s = '  abc  ';

s.trim() // "abc"
s.trimStart() // "abc  "
s.trimEnd() // "  abc"
----------------------------------------------
'aabbcc'.replace('b', '_')
'aabbcc'.replaceAll('b', '_')
-------------------------------
const str = 'hello';
str.at(1) // "e"
str.at(-1) // "o"

正则
var  a=RegExp()
Number.isFinite(), Number.isNaN()
函数释义:
传统的全局方法isFinite()和isNaN()的区别在于,传统方法先调用Number()将非数值的值转为数值,再进行判断,E6中的只数值有效
Number.isFinite()用来检查一个数值是否为有限的(finite),即不是Infinity
Number.isNaN()用来检查一个值是否为NaN

示例:
Number.isFinite(15); // true
Number.isNaN(NaN) // true
Number.parseInt(), Number.parseFloat(),Number.isInteger(),Number.EPSILON,Number.isSafeInteger()
函数释义:
E5是一致的
Number.isInteger():用来判断一个数值是否为整数。
Number.EPSILON:根据规格,它表示 1 与大于 1 的最小浮点数之间的差
Number.isSafeInteger():在整数范围在-2^532^53之间(不含两个端点)
Math.trunc方法用于去除一个数的小数部分,返回整数部分。
Math.sign方法用来判断一个数到底是正数、负数、还是零。对于非数值,会先将其转换为数值。
参数为正数,返回+1;
参数为负数,返回-1;
参数为 0,返回0;
参数为-0,返回-0;
其他值,返回NaN。
Math.cbrt()方法用于计算一个数的立方根。
Math.clz32()方法将参数转为 32 位无符号整数的形式,然后返回这个 32 位值里面有多少个前导 0
Math.imul方法返回两个数以 32 位带符号整数形式相乘的结果,返回的也是一个 32 位的带符号整数。
Math.fround方法返回一个数的32位单精度浮点数形式。
Math.hypot方法返回所有参数的平方和的平方根
BigInt函数,可以用它生成 BigInt 类型的数值
示例:
// ES6的写法
Number.parseInt('12.34') // 12
Number.parseFloat('123.45#') // 123.45
Number.isInteger(25.1) // false
Number.isSafeInteger(3) // true
Math.fround(1.125) // 1.125
Math.imul(2, 4)   // 8
Math.cbrt(1)  // 1
Math.sign(5) // +1
Math.trunc(4.1) // 4



函数扩充
函数释义:
rest 参数:用于获取函数的多余参数
函数的name属性,返回该函数的函数名。
ES6 允许使用“箭头”(=>)定义函数。

示例:
function push(array, ...items) {
  items.forEach(function(item) {
    array.push(item);
    console.log(item);
  });
}

var a = [];
push(a, 1, 2, 3)
----------------------------
const bar = function baz() {};

// ES5
bar.name // "baz"

// ES6
bar.name // "baz"
----------------------------------
var sum = (num1, num2) => num1 + num2;
// 等同于
var sum = function(num1, num2) {
  return num1 + num2;
};
异常捕获
try {
  // ...
} catch (err) {
  // 处理错误
}
数组扩展
释义
Array.from()用于将两类对象转为真正的数组
Array.of()将一组值,转换为数组
arr1.concat(arr2, arr3);数组合并的新写法
Array.prototype.copyWithin(target, start = 0, end = this.length)
target(必需):从该位置开始替换数据。如果为负值,表示倒数。
start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。
end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算。
find()数组实例的find()方法,用于找出第一个符合条件的数组成员
findIndex()findIndex()方法的用法与find()方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1
findLast()findLastIndex()findLast()和findLastIndex()从数组结尾开始,寻找第一个value属性为奇数的成员。结果,该成员是{ value: 3 },位置是2号位
fill()fill方法使用给定值,填充一个数组。
entries():遍历下标和值
keys() :遍历下标
values():遍历值
includes():Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值
flat():将嵌套的数组“拉平”,可以进行多层拉平
flatMap()
at()接受一个整数作为参数,返回对应位置的成员,并支持负索引
group()是一个分组函数,原数组的每个成员都会依次执行这个函数,确定自己是哪一个组。
groupToMap()作用和用法与group()完全一致,唯一的区别是返回值是一个 Map 结构,而不是对象
Array.prototype.sort() 按照首字母进行排序
toReversed()对应reverse(),用来颠倒数组成员的位置。
toSorted()对应sort(),用来对数组成员排序。
toSpliced()对应splice(),用来在指定位置,删除指定数量的成员,并插入新成员。
with(index, value)对应splice(index, 1, value),用来将指定位置的成员替换为新的值。
示例
// ES6 的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
----------------------------------------------------
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];

// ES5 的合并数组
arr1.concat(arr2, arr3);
--------------------------------------------------
Array.of(3, 11, 8) // [3,11,8]
--------------------------------------------------
[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]

--------------------------------------------------
[1, 4, -5, 10].find((n) => n < 0)
// -5
--------------------------------------------------
[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2
--------------------------------------------------
['a', 'b', 'c'].fill(7)
// [7, 7, 7]
--------------------------------------------------
for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"
--------------------------------------------------
[1, 2, 3].includes(2)     // true
--------------------------------------------------
[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]
--------------------------------------------------
// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]
--------------------------------------------------
const arr = [5, 12, 8, 130, 44];
arr.at(2) // 8
arr.at(-2) // 130
--------------------------------------------------
const sequence = [1, 2, 3];
sequence.toReversed() // [3, 2, 1]
sequence // [1, 2, 3]

const outOfOrder = [3, 1, 2];
outOfOrder.toSorted() // [1, 2, 3]
outOfOrder // [3, 1, 2]

const array = [1, 2, 3, 4];
array.toSpliced(1, 2, 5, 6, 7) // [1, 5, 6, 7, 4]
array // [1, 2, 3, 4]

const correctionNeeded = [1, 1, 3];
correctionNeeded.with(1, 2) // [1, 2, 3]
correctionNeeded // [1, 1, 3]
--------------------------------------------------
const array = [1, 2, 3, 4, 5];

array.group((num, index, array) => {
  return num % 2 === 0 ? 'even': 'odd';
});
// { odd: [1, 3, 5], even: [2, 4] }
--------------------------------------------------
const array = [1, 2, 3, 4, 5];

const odd  = { odd: true };
const even = { even: true };
array.groupToMap((num, index, array) => {
  return num % 2 === 0 ? even: odd;
});
//  Map { {odd: true}: [1, 3, 5], {even: true}: [2, 4] }
--------------------------------------------------
Array(3) // [, , ,]
--------------------------------------------------
// forEach方法
[,'a'].forEach((x,i) => console.log(i)); // 1

// filter方法
['a',,'b'].filter(x => true) // ['a','b']

// every方法
[,'a'].every(x => x==='a') // true

// reduce方法
[1,,2].reduce((x,y) => x+y) // 3

// some方法
[,'a'].some(x => x !== 'a') // false

// map方法
[,'a'].map(x => 1) // [,1]

// join方法
[,'a',undefined,null].join('#') // "#a##"

// toString方法
[,'a',undefined,null].toString() // ",a,,"
--------------------------------------------------
const arr = [
  'peach',
  'straw',
  'apple',
  'spork'
];

const stableSorting = (s1, s2) => {
  if (s1[0] < s2[0]) return -1;
  return 1;
};

arr.sort(stableSorting)
// ["apple", "peach", "straw", "spork"]

对象的扩展
释义
Object.is() 比较两个值是否相等
Object.assign()对象的合并
Object.getPrototypeOf() 用于读取一个对象的原型对象
Object.setPrototypeOf() 用来设置一个对象的原型对象(prototype),返回参数对象本身
__proto__属性:用来读取或设置当前对象的原型对象
Object.keys(),Object.values(),Object.entries()
Object.fromEntries()
Object.hasOwn()

示例
Object.is('foo', 'foo')
// true
Object.is({}, {})
--------------------------------------------
// false
const target = { a: 1 };

const source1 = { b: 2 };
const source2 = { c: 3 };

Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
-------------------------------------------------
const obj = {
  __proto__: prot,
  foo: 123,
};
------------------------------------------------
// 用法
const o = Object.setPrototypeOf({}, null);
------------------------------------------------
Object.getPrototypeOf(obj);
------------------------------------------------
var obj = { foo: 'bar', baz: 42 };
Object.keys(obj)
// ["foo", "baz"]

let {keys, values, entries} = Object;
let obj = { a: 1, b: 2, c: 3 };

for (let key of keys(obj)) {
  console.log(key); // 'a', 'b', 'c'
}

for (let value of values(obj)) {
  console.log(value); // 1, 2, 3
}

for (let [key, value] of entries(obj)) {
  console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]
}
const obj = { foo: 'bar', baz: 42 };
Object.values(obj)
// ["bar", 42]
const obj = { foo: 'bar', baz: 42 };
Object.entries(obj)
// [ ["foo", "bar"], ["baz", 42] ]

------------------------------------------------
Object.fromEntries([
  ['foo', 'bar'],
  ['baz', 42]
])
// { foo: "bar", baz: 42 }
------------------------------------------------
const foo = Object.create({ a: 123 });
foo.b = 456;

Object.hasOwn(foo, 'a') // false
Object.hasOwn(foo, 'b') // true

运算符的扩展
释义
**)多个指数运算符连用时,是从最右边开始计算的
(**=)指数运算符可以与等号结合
?.直接在链式调用的时候判断,左侧的对象是否为nullundefined。如果是的,就不再往下运算,而是返回undefined
||=&&=??=多个逻辑运算符一起使用,必须用括号表明优先级,否则会报错。

示例
2 ** 2 // 4
2 ** 3 // 8
------------------------------------------------------------------------
let a = 1.5;
a **= 2;
// 等同于 a = a * a;

let b = 4;
b **= 3;
// 等同于 b = b * b * b;

------------------------------------------------------------------------
const firstName = message?.body?.user?.firstName || 'default';
const fooValue = myForm.querySelector('input[name=foo]')?.value
obj?.prop // 对象属性是否存在
obj?.[expr] // 同上
func?.(...args) // 函数或对象方法是否存在
a?.b
// 等同于
a == null ? undefined : a.b

a?.[x]
// 等同于
a == null ? undefined : a[x]

a?.b()
// 等同于
a == null ? undefined : a.b()

a?.()
// 等同于
a == null ? undefined : a()
a?.[++x]
// 等同于
a == null ? undefined : a[++x]
------------------------------------------------------------------------
const headerText = response.settings.headerText ?? 'Hello, world!';
const animationDuration = response.settings.animationDuration ?? 300;
const showSplashScreen = response.settings.showSplashScreen ?? true;
------------------------------------------------------------------------

// 或赋值运算符
x ||= y
// 等同于
x || (x = y)

// 与赋值运算符
x &&= y
// 等同于
x && (x = y)

// Null 赋值运算符
x ??= y
// 等同于
x ?? (x = y)
------------------------------------------------------------------------
function example(opts) {
  opts.foo ??= 'bar';
  opts.baz ??= 'qux';
}
  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知青先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值