标签:函数返回 col 指定 world 文档 布尔值 node undefined typeerror
解构:ES6允许按照一定模式从数据和对象中提取值来对变量进行赋值
let [a, b, c] = [1, 2, 3];
let [x, , y] = [1, 2, 3]; x // 1 y // 3
如果解构不成功,变量的值就等于undefined
let [x, y, ...z] = [‘a‘]; x // "a" y // undefined z // []
不完全解构,即等号左边的模式,只匹配一部分的等号右边的数组
let [a, [b], d] = [1, [2, 3], 4]; a // 1 b // 2 d // 4
如果等号右边不是可遍历(本身不具备Iterator接口)的解构,那么将会报错
解构赋值允许指定默认值。
注意,ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,只有当一个数组成员严格等于undefined,默认值才会生效。
let [x = 1] = [undefined]; x // 1 let [x = 1] = [null]; x // null
let { foo, bar } = { foo: ‘aaa‘, bar: ‘bbb‘ };
foo // "aaa"
bar // "bbb"
实际上为
let { foo: foo, bar: bar } = { foo: ‘aaa‘, bar: ‘bbb‘ };
foo是匹配的模式,baz才是变量。真正被赋值的是变量baz,而不是模式foo。
let { foo: baz } = { foo: ‘aaa‘, bar: ‘bbb‘ };
baz // "aaa"
foo // error: foo is not defined
默认值生效的条件是,对象的属性值严格等于undefined。
var {x = 3} = {x: undefined}; x // 3 var {x = 3} = {x: null}; x // null
如果要将一个已经声明的变量用于解构赋值,必须非常小心。
// 错误的写法
let x;
{x} = {x: 1};
// SyntaxError: syntax error
// 正确的写法
let x;
({x} = {x: 1});
因为 JavaScript 引擎会将{x}理解成一个代码块,从而发生语法错误。只有不将大括号写在行首,避免 JavaScript 将其解释为代码块,才能解决这个问题。
const [a, b, c, d, e] = ‘hello‘; a // "h" b // "e" c // "l" d // "l" e // "o"
let {length : len} = ‘hello‘;
len // 5
解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
为变量x,y指定默认值
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
为参数指定默认值
function move({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]
let x = 1; let y = 2; [x, y] = [y, x];
// 返回一个数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一个对象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
} = {}) {
// ... do stuff
};
const map = new Map();
map.set(‘first‘, ‘hello‘);
map.set(‘second‘, ‘world‘);
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
const { SourceMapConsumer, SourceNode } = require("source-map");
阮一峰大神:ECMAScript 6 入门
标签:函数返回 col 指定 world 文档 布尔值 node undefined typeerror
原文地址:https://www.cnblogs.com/Mijiujs/p/12084309.html