问:怎么把js数组里面的两个元素调换位置呢?

问:怎么把js数组里面的两个元素调换位置呢?

答:解构赋值

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let str = ['a', 'b', 'c', 'd'];
        [str[1], str[2]] = [str[2], str[1]];
        console.log(str); // (4) ["a", "c", "b", "d"]
    </script>
</body>

</html>

你可能感兴趣的:(前端面试,Javascript)