Products
GG网络技术分享 2025-03-18 16:14 2
此外还要注意这里不一定就是正式进入规范的语法。
在我们开发的时候,可能认为应该默认使用 let 而不是 var,这种情况下,对于需要写保护的变量要使用 const。
然而另一种做法日益普及:默认使用 const,只有当确实需要改变变量的值的时候才使用 let。这是因为大部分的变量的值在初始化后不应再改变,而预料之外的变量的修改是很多 bug 的源头。
// 例子 1-1
// bad
var foo = 'bar';
// good
let foo = 'bar';
// better
const foo = 'bar';
复制代码
需要拼接字符串的时候尽量改成使用模板字符串:
// 例子 2-1
// bad
const foo = 'this is a' + example;
// good
const foo = `this is a ${example}`;
复制代码
可以借助标签模板优化书写方式:
// 例子 2-2
let url = oneLine `
www.taobao.com/example/index.html
?foo=${foo}
&bar=${bar}
`;
console.log(url);
复制代码
oneLine 的源码可以参考 《ES6 系列之模板字符串》
https://github.com/mqyqingfeng/Blog/issues/109
优先使用箭头函数,不过以下几种情况避免使用:
// 例子 3-1
// bad
let foo = {
value: 1,
getValue: () => console.log(this.value)
}
foo.getValue(); // undefined
复制代码
// 例子 3-2
// bad
function Foo() {
this.value = 1
}
Foo.prototype.getValue = () => console.log(this.value)
let foo = new Foo()
foo.getValue(); // undefined
复制代码
// 例子 3-3
// bad
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
console.log(this === window); // => true
this.innerHTML = 'Clicked button';
});
复制代码
// 例子 4-1
// bad
// 1. 创建的属性会被 for-in 或 Object.keys() 枚举出来
// 2. 一些库可能在将来会使用同样的方式,这会与你的代码发生冲突
if (element.isMoving) {
smoothAnimations(element);
}
element.isMoving = true;
// good
if (element.__$jorendorff_animation_library$PLEASE_DO_NOT_USE_THIS_PROPERTY$isMoving__) {
smoothAnimations(element);
}
element.__$jorendorff_animation_library$PLEASE_DO_NOT_USE_THIS_PROPERTY$isMoving__ = true;
// better
var isMoving = Symbol("isMoving");
...
if (element[isMoving]) {
smoothAnimations(element);
}
element[isMoving] = true;
复制代码
魔术字符串指的是在代码之中多次出现、与代码形成强耦合的某一个具体的字符串或者数值。
魔术字符串不利于修改和维护,风格良好的代码,应该尽量消除魔术字符串,改由含义清晰的变量代替。
// 例子 4-1
// bad
const TYPE_AUDIO = 'AUDIO'
const TYPE_VIDEO = 'VIDEO'
const TYPE_IMAGE = 'IMAGE'
// good
const TYPE_AUDIO = Symbol()
const TYPE_VIDEO = Symbol()
const TYPE_IMAGE = Symbol()
function handleFileResource(resource) {
switch(resource.type) {
case TYPE_AUDIO:
playAudio(resource)
break
case TYPE_VIDEO:
playVideo(resource)
break
case TYPE_IMAGE:
previewImage(resource)
break
default:
throw new Error('Unknown type of resource')
}
}
复制代码
Symbol 也可以用于私有变量的实现。
// 例子 4-3
const Example = (function() {
var _private = Symbol('private');
class Example {
constructor() {
this[_private] = 'private';
}
getName() {
return this[_private];
}
}
return Example;
})();
var ex = new Example();
console.log(ex.getName()); // private
console.log(ex.name); // undefined
复制代码
// 例子 5-1
[...new Set(array)]
复制代码
// 例子 5-2
// 根据颜色找出对应的水果
// bad
function test(color) {
switch (color) {
case 'red':
return ['apple', 'strawberry'];
case 'yellow':
return ['banana', 'pineapple'];
case 'purple':
return ['grape', 'plum'];
default:
return [];
}
}
test('yellow'); // ['banana', 'pineapple']
复制代码
// good
const fruitColor = {
red: ['apple', 'strawberry'],
yellow: ['banana', 'pineapple'],
purple: ['grape', 'plum']
};
function test(color) {
return fruitColor[color] || [];
}
复制代码
// better
const fruitColor = new Map()
.set('red', ['apple', 'strawberry'])
.set('yellow', ['banana', 'pineapple'])
.set('purple', ['grape', 'plum']);
function test(color) {
return fruitColor.get(color) || [];
}
复制代码
for...of 循环可以使用的范围包括:
ES2015 引入了 for..of 循环,它结合了 forEach 的简洁性和中断循环的能力:
// 例子 6-1
for (const v of ['a', 'b', 'c']) {
console.log(v);
}
// a b c
for (const [i, v] of ['a', 'b', 'c'].entries()) {
console.log(i, v);
}
// 0 "a"
// 1 "b"
// 2 "c"
复制代码
// 例子 6-2
let map = new Map(arr);
// 遍历 key 值
for (let key of map.keys()) {
console.log(key);
}
// 遍历 value 值
for (let value of map.values()) {
console.log(value);
}
// 遍历 key 和 value 值(一)
for (let item of map.entries()) {
console.log(item[0], item[1]);
}
// 遍历 key 和 value 值(二)
for (let [key, value] of data) {
console.log(key)
}
复制代码
// 例子 7-1
// bad
request(url, function(err, res, body) {
if (err) handleError(err);
fs.writeFile('1.txt', body, function(err) {
request(url2, function(err, res, body) {
if (err) handleError(err)
})
})
});
// good
request(url)
.then(function(result) {
return writeFileAsynv('1.txt', result)
})
.then(function(result) {
return request(url2)
})
.catch(function(e){
handleError(e)
});
复制代码
// 例子 7-2
fetch('file.json')
.then(data => data.json())
.catch(error => console.error(error))
.finally(() => console.log('finished'));
复制代码
// 例子 8-1
// good
function fetch() {
return (
fetchData()
.then(() => {
return "done"
});
)
}
// better
async function fetch() {
await fetchData()
return "done"
};
复制代码
// 例子 8-2
// good
function fetch() {
return fetchData()
.then(data => {
if (data.moreData) {
return fetchAnotherData(data)
.then(moreData => {
return moreData
})
} else {
return data
}
});
}
// better
async function fetch() {
const data = await fetchData()
if (data.moreData) {
const moreData = await fetchAnotherData(data);
return moreData
} else {
return data
}
};
复制代码
// 例子 8-3
// good
function fetch() {
return (
fetchData()
.then(value1 => {
return fetchMoreData(value1)
})
.then(value2 => {
return fetchMoreData2(value2)
})
)
}
// better
async function fetch() {
const value1 = await fetchData()
const value2 = await fetchMoreData(value1)
return fetchMoreData2(value2)
};
复制代码
// 例子 8-4
// good
function fetch() {
try {
fetchData()
.then(result => {
const data = JSON.parse(result)
})
.catch((err) => {
console.log(err)
})
} catch (err) {
console.log(err)
}
}
// better
async function fetch() {
try {
const data = JSON.parse(await fetchData())
} catch (err) {
console.log(err)
}
};
复制代码
// 例子 8-5
// bad
(async () => {
const getList = await getList();
const getAnotherList = await getAnotherList();
})();
// good
(async () => {
const listPromise = getList();
const anotherListPromise = getAnotherList();
await listPromise;
await anotherListPromise;
})();
// good
(async () => {
Promise.all([getList(), getAnotherList()]).then(...);
})();
复制代码
构造函数尽可能使用 Class 的形式
// 例子 9-1
class Foo {
static bar () {
this.baz();
}
static baz () {
console.log('hello');
}
baz () {
console.log('world');
}
}
Foo.bar(); // hello
复制代码
// 例子 9-2
class Shape {
constructor(width, height) {
this._width = width;
this._height = height;
}
get area() {
return this._width * this._height;
}
}
const square = new Shape(10, 10);
console.log(square.area); // 100
console.log(square._width); // 10
复制代码
// 例子 10-1
class Math {
@log
add(a, b) {
return a + b;
}
}
复制代码
log 的实现可以参考 《ES6 系列之我们来聊聊装饰器》
// 例子 10-2
class Toggle extends React.Component {
@autobind
handleClick() {
console.log(this)
}
render() {
return (
<button onClick={this.handleClick}>
button
</button>
);
}
}
复制代码
autobind 的实现可以参考 《ES6 系列之我们来聊聊装饰器》
// 例子 10-3
class Toggle extends React.Component {
@debounce(500, true)
handleClick() {
console.log('toggle')
}
render() {
return (
<button onClick={this.handleClick}>
button
</button>
);
}
}
复制代码
debounce 的实现可以参考 《ES6 系列之我们来聊聊装饰器》
// 例子 10-4
// good
class MyReactComponent extends React.Component {}
export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);
// better
@connect(mapStateToProps, mapDispatchToProps)
export default class MyReactComponent extends React.Component {};
复制代码
// 例子 11-1
// bad
function test(quantity) {
const q = quantity || 1;
}
// good
function test(quantity = 1) {
...
}
复制代码
// 例子 11-2
doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 });
// bad
function doSomething(config) {
const foo = config.foo !== undefined ? config.foo : 'Hi';
const bar = config.bar !== undefined ? config.bar : 'Yo!';
const baz = config.baz !== undefined ? config.baz : 13;
}
// good
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) {
...
}
// better
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) {
...
}
复制代码
// 例子 11-3
// bad
const Button = ({className}) => {
const classname = className || 'default-size';
return <span className={classname}></span>
};
// good
const Button = ({className = 'default-size'}) => (
<span className={classname}></span>
);
// better
const Button = ({className}) =>
<span className={className}></span>
}
Button.defaultProps = {
className: 'default-size'
}
复制代码
// 例子 11-4
const required = () => {throw new Error('Missing parameter')};
const add = (a = required(), b = required()) => a + b;
add(1, 2) // 3
add(1); // Error: Missing parameter.
复制代码
// 例子 12-1
// bad
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort();
}
// good
const sortNumbers = (...numbers) => numbers.sort();
复制代码
// 例子 12-2
// bad
Math.max.apply(null, [14, 3, 77])
// good
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77);
复制代码
剔除部分属性,将剩下的属性构建一个新的对象
// 例子 12-3
let [a, b, ...arr] = [1, 2, 3, 4, 5];
const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4, e: 5 };
复制代码
有条件的构建对象
// 例子 12-4
// bad
function pick(data) {
const { id, name, age} = data
const res = { guid: id }
if (name) {
res.name = name
}
else if (age) {
res.age = age
}
return res
}
// good
function pick({id, name, age}) {
return {
guid: id,
...(name && {name}),
...(age && {age})
}
}
复制代码
合并对象
// 例子 12-5
let obj1 = { a: 1, b: 2,c: 3 }
let obj2 = { b: 4, c: 5, d: 6}
let merged = {...obj1, ...obj2};
复制代码
将对象全部传入组件
// 例子 12-6
const parmas = {value1: 1, value2: 2, value3: 3}
<Test {...parmas} />
复制代码
// 例子 13-1
foo::bar;
// 等同于
bar.bind(foo);
foo::bar(...arguments);
// 等同于
bar.apply(foo, arguments);
复制代码
如果双冒号左边为空,右边是一个对象的方法,则等于将该方法绑定在该对象上面。
// 例子 13-2
var method = obj::obj.foo;
// 等同于
var method = ::obj.foo;
let log = ::console.log;
// 等同于
var log = console.log.bind(console);
复制代码
// 例子 14-1
componentWillReceiveProps(newProps) {
this.setState({
active: newProps.active
})
}
componentWillReceiveProps({active}) {
this.setState({active})
}
复制代码
// 例子 14-2
// bad
handleEvent = () => {
this.setState({
data: this.state.data.set("key", "value")
})
};
// good
handleEvent = () => {
this.setState(({data}) => ({
data: data.set("key", "value")
}))
};
复制代码
// 例子 14-3
Promise.all([Promise.resolve(1), Promise.resolve(2)])
.then(([x, y]) => {
console.log(x, y);
});
复制代码
// 例子 14-4
// bad
function test(fruit) {
if (fruit && fruit.name) {
console.log (fruit.name);
} else {
console.log('unknown');
}
}
// good
function test({name} = {}) {
console.log (name || 'unknown');
}
复制代码
// 例子 14-5
let obj = {
a: {
b: {
c: 1
}
}
};
const {a: {b: {c = ''} = ''} = ''} = obj;
复制代码
// 例子 14-6
// bad
const spliteLocale = locale.splite("-");
const language = spliteLocale[0];
const country = spliteLocale[1];
// good
const [language, country] = locale.splite('-');
复制代码
// 例子 14-8
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
console.log(baz); // "aaa"
复制代码
// 例子 14-9
function test(input) {
return [left, right, top, bottom];
}
const [left, __, top] = test(input);
function test(input) {
return { left, right, top, bottom };
}
const { left, right } = test(input);
复制代码
// 例子 15-1
// bad
const something = 'y'
const x = {
something: something
}
// good
const something = 'y'
const x = {
something
};
复制代码
动态属性
// 例子 15-2
const x = {
['a' + '_' + 'b']: 'z'
}
console.log(x.a_b); // z
复制代码
// 例子 16-1
var arr = ["a", , "c"];
var sparseKeys = Object.keys(arr);
console.log(sparseKeys); // ['0', '2']
var denseKeys = [...arr.keys()];
console.log(denseKeys); // [0, 1, 2]
复制代码
// 例子 16-2
var arr = ["a", "b", "c"];
var iterator = arr.entries();
for (let e of iterator) {
console.log(e);
}
复制代码
// 例子 16-3
let arr = ['w', 'y', 'k', 'o', 'p'];
let eArr = arr.values();
for (let letter of eArr) {
console.log(letter);
}
复制代码
// 例子 16-4
// bad
function test(fruit) {
if (fruit == 'apple' || fruit == 'strawberry') {
console.log('red');
}
}
// good
function test(fruit) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (redFruits.includes(fruit)) {
console.log('red');
}
}
复制代码
// 例子 16-5
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
复制代码
// 例子 16-6
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
复制代码
更多的就不列举了。
举个例子:
// 例子 17-1
const obj = {
foo: {
bar: {
baz: 42,
},
},
};
const baz = obj?.foo?.bar?.baz; // 42
复制代码
同样支持函数:
// 例子 17-2
function test() {
return 42;
}
test?.(); // 42
exists?.(); // undefined
复制代码
需要添加 @babel/plugin-proposal-optional-chaining 插件支持
// 例子 18-1
a ||= b;
obj.a.b ||= c;
a &&= b;
obj.a.b &&= c;
复制代码
Babel 编译为:
var _obj$a, _obj$a2;
a || (a = b);
(_obj$a = obj.a).b || (_obj$a.b = c);
a && (a = b);
(_obj$a2 = obj.a).b && (_obj$a2.b = c);
复制代码
出现的原因:
// 例子 18-2
function example(a = b) {
// a 必须是 undefined
if (!a) {
a = b;
}
}
function numeric(a = b) {
// a 必须是 null 或者 undefined
if (a == null) {
a = b;
}
}
// a 可以是任何 falsy 的值
function example(a = b) {
// 可以,但是一定会触发 setter
a = a || b;
// 不会触发 setter,但可能会导致 lint error
a || (a = b);
// 就有人提出了这种写法:
a ||= b;
}
复制代码
需要 @babel/plugin-proposal-logical-assignment-operators 插件支持
a ?? b
// 相当于
(a !== null && a !== void 0) ? a : b
复制代码
举个例子:
var foo = object.foo ?? "default";
// 相当于
var foo = (object.foo != null) ? object.foo : "default";
复制代码
需要 @babel/plugin-proposal-nullish-coalescing-operator 插件支持
const double = (n) => n * 2;
const increment = (n) => n + 1;
// 没有用管道操作符
double(increment(double(5))); // 22
// 用上管道操作符之后
5 |> double |> increment |> double; // 22
复制代码新开了 知乎专栏,大家可以在更多的平台上看到我的文章,欢迎关注哦~
ES6 系列目录地址:https://github.com/mqyqingfeng/Blog
ES6 系列预计写二十篇左右,旨在加深 ES6 部分知识点的理解,重点讲解块级作用域、标签模板、箭头函数、Symbol、Set、Map 以及 Promise 的模拟实现、模块加载方案、异步处理等内容。
如果有错误或者不严谨的地方,请务必给予指正,十分感谢。如果喜欢或者有所启发,欢迎 star,对作者也是一种鼓励。
原链接:https://juejin.im/post/5bfe05505188252098022400
主要介绍了ES6对象操作,结合实例形式详细分析了ES6对象创建、赋值、比较、合并等相关操作技巧与注意事项,需要的朋友可以参考下
1.对象赋值
es5中的对象赋值方式如下:
let name=\"小明\"; let skill= \'es6开发\'; var obj= {name:name,skill:skill}; console.log(obj); |
结果为:
ES6允许把声明的变量直接赋值给对象,例如:
let name=\"小明\"; let skill= \'es6开发\'; var obj= {name,skill}; console.log(obj); |
结果与上述相同。
2.对象Key值构建
有时候我们会在后台取出key值,而不是我们前台定义好的,这时候我们可以我们可以把后台定义的key值重新构建返回给后台。
在前端我们可以用[ ] 的形式,进行对象的构建。
let key=\'skill\';//假定是后台定义的key值 var obj={ [key]:\'web\' //构建key值 } console.log(obj.skill);//web |
3.自定义对象方法
对象方法就是把对象中的属性,用匿名函数的形式编程方法。
var obj={ add:function(a,b){ return a+b; } } console.log(obj.add(1,2)); //3 |
4.Object.is( ) 对象比较
ES5的对象比较方法,经常使用===来判断,如下:
var obj1 = {name:\'admin\'}; var obj2 = {name:\'admin\'}; console.log(obj1.name === obj2.name);//true |
ES6为我们提供了is方法进行对比,如下:
var obj1 = {name:\'admin\'}; var obj2 = {name:\'admin\'}; console.log(Object.is(obj1.name,obj2.name))//true |
区分=== 和 is方法的区别是什么,看下面的代码输出结果。
console.log(+0 === -0); //true console.log(NaN === NaN ); //false<br><br> console.log(Object.is(+0,-0)); //false console.log(Object.is(NaN,NaN)); //true |
记忆为:===为同值相等,is()为严格相等。
6.Object.assign( )合并对象
使用assgin( )可以实现像数组一样的合并操作。
var a={a:\'a\'}; var b={b:\'b\'}; var c={c:\'c\'}; let d=Object.assign(a,b,c) console.log(d); |
结果为:
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。希望本文所述对大家JavaScript程序设计有所帮助。
Demand feedback