• 技术文章 >web前端 >前端问答

    es6解构支持字符串吗

    青灯夜游青灯夜游2022-10-24 18:50:48原创141

    es6解构支持字符串。ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构;通过解构赋值可以将属性值从对象/数组中取出赋值给其他变量。字符串也可以解构赋值,字符串会被转换成了一个类似数组的对象;类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。

    大前端零基础入门到就业:进入学习

    本教程操作环境:windows10系统、ECMAScript 6版、Dell G3电脑。

    es6的解构是什么意思

    destructuring:百度百科的意思是结构分解,ES6 中允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。

    解构赋值语法是一种 Javascript 表达式,通过解构赋值可以将属性值从对象/数组中取出赋值给其他变量

    ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构

    开发中比较常见的有字符串解构、对象解构、 数组解构、混合解构。这是一种将数据结构分解为更小的部分的过程,从而达到简化提取信息的目的。

    1. 基本数据类型解构

    1-1 字符串解构赋值

    字符串也可以解构赋值,字符串会被转换成了一个类似数组的对象

    类似数组的对象都有一个length 属性,因此还可以对这个属性解构赋值

    // 会将字符串转换成一个类数组对象
    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

    1-2 数值、布尔值解构赋值

    解构赋值时,如果等号右边是数值和布尔值,则会先转为对象

    解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象

    数值和布尔值的包装对象都有 toString 属性,变量都能取到值

    let {toString: s} = 123;
    s === Number.prototype.toString // true
    
    let {toString: s} = true;
    s === Boolean.prototype.toString // true

    由于 undefinednull 无法转为对象,所以对它们进行解构赋值,都会报错

    let { prop: x } = undefined; // TypeError
    let { prop: y } = null; // TypeError

    2. 数组解构

    2-1 基本用法

    // 数组可以在变量声明并赋值时解构
    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

    2-2 完全解构

    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
    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

    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
    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

    2-4 默认值

    let [name1 = 'jsx', name2 = 'ljj'] = [];
    console.log(name1, name2); // jsx ljj
    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

    3. 对象解构

    3-1 基本用法

    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

    3-2 属性变量同名

    let {name, age} = {name: 'jsx', age: 22};
    console.log(name, age); // jsx 22
    // 如果解构失败,变量的值等于undefined
    let {a, b} = {a: 'jsx', c: 'ljj'};
    console.log(a, b); // jsx undefined

    3-3 属性变量不同名

    let {user: name, age: num} = {user: 'jsx', age: 22}
    console.log(name, num); // jsx 22
    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

    3-4 默认值

    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
    let {user: xm = 'jsx'} = {};
    console.log(xm); // jsx

    4. 嵌套解构

    如果一个对象或数组嵌套了其他的对象和数组,我们可以在等号左侧使用更复杂的模式(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: '新消息'}
    // 新消息

    5. 函数参数解构

    一个函数可以有很多参数,其中大部分的参数都是可选的

    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();

    6. 圆括号问题

    不可以使用圆括号的情况:

    // 声明语句时不能使用圆括号包裹变量
    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

    7. 解构赋值使用场景

    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'})
    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(); // 默认值
    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
    }
    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视频教程编程视频

    以上就是es6解构支持字符串吗的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

    前端(VUE)零基础到就业课程:点击学习

    清晰的学习路线+老师随时辅导答疑

    自己动手写 PHP MVC 框架:点击学习

    快速了解MVC架构、了解框架底层运行原理

    专题推荐:javascript ES6
    上一篇:使用es6怎么实现两个变量的转换 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • ❤️‍🔥共22门课程,总价3725元,会员免费学• ❤️‍🔥接口自动化测试不想写代码?• es6的class继承为什么要调用super• es6数组中可以用展开符吗• es6语法是一种标准吗• class类是es6语法么• es6中数组可以用for of遍历吗• es6中for和foreach的区别是什么
    1/1

    PHP中文网