Home > Article > Web Front-end > Does es6 destructuring support strings?
es6 destructuring supports strings. ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called destructuring; through destructuring assignment, attribute values can be taken out of objects/arrays and assigned to other variables. Strings can also be destructured and assigned, and the string will be converted into an array-like object; array-like objects have a length attribute, so this attribute can also be destructured and assigned.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6, Dell G3 computer.
destructuring: Baidu Encyclopedia means structural decomposition. ES6 allows extracting values from arrays and objects according to certain patterns. Variables are assigned values, which is called destructuring.
Destructuring assignment syntax is a Javascript expression. Through destructuring assignment, attribute values can be taken out from objects/arrays and assigned to other variables.
ES6 allows you to extract values from arrays and objects according to certain patterns. Extracting values and assigning values to variables is called destructuring
The more common ones in development include string destructuring, object destructuring, array destructuring, and mixed destructuring. This is a process of breaking down a data structure into smaller parts to simplify the extraction of information.
Strings can also be destructured and assigned. The string will be converted into an array-like object
Array-like objects have a length
attribute, so this attribute can also be deconstructed and assigned a value
// 会将字符串转换成一个类数组对象 let [a, b, c, d ,e] = 'hello'; console.log(a, b, c, d ,e); // h e l l o // 类数组对象lenth 属性解构 let {length : num} = 'hello'; console.log(num); // 5
When destructuring assignment, if the right side of the equal sign is a numerical value or Boolean value, it will be converted to an object first
Rules for destructuring assignment Yes, as long as the value on the right side of the equal sign is not an object or array, convert it to an object first
The packaging objects of numerical and Boolean values have the toString
attribute, and the variables can get the value
let {toString: s} = 123; s === Number.prototype.toString // true let {toString: s} = true; s === Boolean.prototype.toString // true
Since undefined
and null
cannot be converted into objects, destructuring and assigning them will result in an error
let { prop: x } = undefined; // TypeError let { prop: y } = null; // TypeError
// 数组可以在变量声明并赋值时解构 let arr = ['jsx', 'ljj', 'zdj', 'ddc'] let [one, two, three, four] = arr; console.log(one, two, three, four); // jsx ljj zdj ddc // 也可以在变量先声明后赋值解构 let name1, name2, name3, name4; [name1, name2, name3, name4] = ['jsx', 'ljj', 'zdj', 'ddc']; console.log(name1, name2, name3, name4); // jsx ljj zdj ddc
let [one, two, three] = ['html', 'css', 'js']; console.log(one, two, three); // html css js let [str1, [str2], str3] = ['jsx', ['ljj'], 'ddc'] console.log(str1, str2, str3); // jsx ljj ddc
,
来忽略let [, , name] = ['haha', 'xixi', 'jsx']; console.log(name); // jsx let [, xixi , ] = ['haha', 'xixi', 'jsx']; console.log(xixi); // xixi
...
,将数组剩余部分赋值给一个变量let [num, ...numN] = [1, 2, 3, 4]; console.log(num); // 1 console.log(numN); // [2, 3, 4]
let name1 = 'jsx'; let name2 = 'ljj'; let name3 = 'ddc'; [name1, name2, name3] = [name3, name1, name2]; console.log(name1, name2, name3); // ddc jsx ljj
Iterator
接口对象或数组)let [a, b, c] = 'jsx'; console.log(a, b, c); // j s x let [one1, two1, three1] = new Set([1, 2, 3]); console.log(one1, two1, three1); // 1 2 3
let [one, two] = [1, 2, 3]; console.log(one, two); // 1 2 let [a, [b], c] = [1, [2, 3], 4] console.log(a, b, c); // 1 2 4
undefined
let [str1, str2] = ['jsx']; console.log(str1, str2); // jsx undefined
...
变量解构时匹配不到元素值时返回 []
空数组let [str3, ...str4] = ['jsx']; console.log(str3, str4); // jsx []
let [foo1] = 1; let [foo2] = false; let [foo3] = NaN; let [foo4] = undefined; let [foo5] = null; let [foo6] = {}; console.log(foo1, foo2, foo3, foo4, foo5, foo6); // is not iterable
let [name1 = 'jsx', name2 = 'ljj'] = []; console.log(name1, name2); // jsx ljj
ES6
内部使用严格相等运算符 ===
判断一个位置是否有值,当一个数组缺少的值时,元素严格等于undefined
,默认值才会生效let [num = 123] = [undefined]; console.log(num); // 123 // null !== undefined means let [num1 = 123] = [null]; // null严格相等undefined所有默认值无效 console.log(num1); // null
function func() { return 123 } let [num2 = func()] = [undefined]; console.log(num2)
let [str1 = 'jsx', str2 = str1] = []; console.log(str1, str2); // jsx jsx // str4未声明 let [str3 = str4, str4 = 'ljj'] = []; // Uncaught ReferenceError
let {var1, var2} = {var1:…, var2:…}
let { name, age } = { name: 'jsx', age: 22 }; console.log(name, age); // jsx 22 // 先声明后独立解构赋值 let a, b; // 赋值语句需要通过()包围 因为{}是一个块级而不是字面量 ({a, b} = {a: 1, b: 2}); console.log(a, b); // 1 2
let {name, age} = {name: 'jsx', age: 22}; console.log(name, age); // jsx 22
undefined
// 如果解构失败,变量的值等于undefined let {a, b} = {a: 'jsx', c: 'ljj'}; console.log(a, b); // jsx undefined
:
来设置,将对象属性值赋值给 :
冒号后的变量let {user: name, age: num} = {user: 'jsx', age: 22} console.log(name, num); // jsx 22
foo:baz
此时冒号前面 foo
则是匹配模式匹配对象属性,baz
则是匹配属性的值let {foo:baz} = {name: 'jsx'}; console.log(foo); // ncaught ReferenceErro console.log(baz); // undefined
let {name: str, age: num1} = {user: 'jsx', age: 22}; console.log(str, num1); // undefined 22
let obj = { lesson: ['html', { class: 'css' }] } let { lesson: [x, { class: y }] } = obj; // console.log(x, y); // html css let { lesson } = obj; console.log(lesson); // ['html', {…}] let obj1 = {}; let arr1 = []; ({ foo: obj1.prop, bar: arr1[0] } = { foo: 123, bar: true }); console.log(obj1) // {prop:123} console.log(arr1) // [true]
let obj2 = {}; let obj3 = { user: 'ljj' }; Object.setPrototypeOf(obj2, obj3); let { user } = obj2; console.log(user); // ljj
...
将对象剩余的属性与值赋值给一个变量let options = { title: "Menu", height: 200, width: 100 }; // title = 名为 title 的属性 // rest = 存有剩余属性的对象 let { title, ...rest } = options; // 现在 title="Menu", rest={height: 200, width: 100} console.log(rest.height); // 200 console.log(rest.width); // 100
undefined
let {name = 'jsx'} = {}; console.log(name); // jsx let {name1 = 'jsx'} = {name1: 'ljj'}; // 默认值失效 console.log(name1); // ljj // 当对象属性值为undefined时有效 let {name2 = 'jsx'} = {name2: undefined}; console.log(name2); // jsx let {x: y = 3} = {x: 5}; console.log(y); // 5 let {x1 = 3} = {x1: null}; console.log(x1); // null
undefined
时,先匹配属性再在变量值后添加一个等号 =
和相应的默认值即可let {user: xm = 'jsx'} = {}; console.log(xm); // jsx
如果一个对象或数组嵌套了其他的对象和数组,我们可以在等号左侧使用更复杂的模式(pattern)来提取更深层的数据
// 数组嵌套 let [name, [name1, [name2]]] = ['jsx', ['ljj', ['ddc']]]; console.log(name, name1, name2); // jsx ljj ddc // 对象解构 let obj = { title: '对象解构', info: { target: '对象', difficulty: { level: 1 } } } let { title, info, info: { target, difficulty, difficulty: { level } } } = obj; console.log(title, info, target, difficulty, level); // 对象解构 // {target: '对象', difficulty: {…}} // 对象 // {level: 1} // 1 // 对象数组嵌套 let objArr = { message: '对象数组嵌套', lesson: ['html', 'css', 'js'], news: { main: '新消息' } } let { message, lesson, lesson: [item1, item2, item3], news, news: { main } } = objArr; console.log(message, lesson, item1, item2, item3, news, main) // 对象数组嵌套 // ['html', 'css', 'js'] // html css js // {main: '新消息'} // 新消息
一个函数可以有很多参数,其中大部分的参数都是可选的
function arrFn([name, age]) { console.log(name, age) } arrFn(['jsx', 22]); // jsx 22
let obj = { title: "My menu", items: ["Item1", "Item2"] } function objFn({ title, items: [item1, item2] }) { console.log(title); // My menu console.log(item1, item2); // Item1 Item2 } objFn(obj);
// 语法 function({ incomingProperty: varName = defaultValue ... }) let obj1 = { message: '嵌套带冒号', info: { name: 'jsx', lesson: ['html', 'css'], grilfriend: { xm: 'ljj' } } } function complexFn({ message, info: { name, lesson: [list1, list2], grilfriend: { xm } } }) { console.log(message); // 嵌套带冒号 console.log(list1, list2); // html css console.log(xm); // ljj } complexFn(obj1);
{}
为整个参数对象设置默认值function nullFn({ info = 'jsx', width = 100, height = 200 } = {}) { console.log(info); // jsx console.log(width); // 100 console.log(height); // 200 } nullFn();
不可以使用圆括号的情况:
变量声明语句,不得使用圆括号
函数参数也属于变量声明,因此不能带有圆括号
赋值语句的模式,将整个模式放在圆括号之中,导致报错
// 声明语句时不能使用圆括号包裹变量 let [(num)] = [1]; console.log(a); // Uncaught SyntaxError let {(name: str)} = {name: 'jsx'}; console.log(str); // Uncaught SyntaxError // 函数参数内也不可以 function fn([(a)]) { console.log(a); } fn(1); // 赋值语句内不可使用圆括号包裹 let a, b; ([a, b]) = [1, 2]; console.log(a, b) // Uncaught SyntaxError
可以使用圆括号的情况:
let num; [(num)] = [123]; console.log(num); // 123 let str; ({name: str} = {name: 'jsx'}); console.log(str); // jsx
let name1 = 'jsx'; let name2 = 'ljj'; [name1, name2] = [name2, name1]; console.log(name1, name2); // ljj, jsx
function returnFn() { return { name: 'jsx', age: 22 } } let { name, age } = returnFn(); console.log(name, age); // jsx 22
function argumentFn([list1, list2]) { console.log(list1); // jsx console.log(list2); // ljj } argumentFn(['jsx', 'ljj']) function argumentFn1({obj}) { console.log(obj); // jsx } argumentFn1({obj: 'jsx'})
JSON
数据let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); // 42 'OK' (2) [867, 5309]
function func({ title = '默认值' } = {}) { console.log(title) } func(); // 默认值
Map
结构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 }
.entries()
方法进行循环操作let user = { name: "John", age: 30 }; for (let [key, value] of Object.entries(user)) { console.log(`${key}: ${value}`); // name: John // age: 30 }
<script type="module"> import {sayHi, sayHello} from './index.js'; sayHi(); // say hi sayHello(); // say hello </script>
// index.js export function sayHi() { console.log('say hi') } export function sayHello() { console.log('say hello') }
【相关推荐:javascript视频教程、编程视频】
The above is the detailed content of Does es6 destructuring support strings?. For more information, please follow other related articles on the PHP Chinese website!