16.16.尚硅谷_JS基础_一元运算符

119 阅读1分钟

16.16.尚硅谷_JS基础_ 一元运算符

一、潜在作用

1、正号:对数字没啥卵用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        var a = 123;//正正为正

        a = +a ;
        console.log(a);
        console.log( typeof a);

        var a = -123;//负正为负

        a = +a ;
        console.log(a);
        console.log( typeof a);


    </script>
</head>
<body>
    
</body>
</html>

image-20211105225309971

2、负号:对数字惊醒负号取反

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        var a = 123;

        a = -a ;
        console.log(a);
        console.log( typeof a);

        var a = -123;//负负为正

        a = -a ;
        console.log(a);
        console.log( typeof a);


    </script>
</head>
<body>
    
</body>
</html>

image-20211105225223284

二、真实作用:

对于非Number类型的值,它会将==先==转换为==Number==,然后再运算

  • 可以对一个其他的数据类型使用 + ,来将其转换为number
  • 它的原理和==Number()函数==一样
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        var a = 123;

        a = true;

        a = +a ;
        console.log("a = " + a);
        console.log(typeof a)
    </script>
</head>
<body>
    
</body>
</html>

image-20211105230159613

实际案例:(+ 可以把任何数据类型变成 number 数据类型)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>

        //初始状态
        a = 1 + "2" + 3;
        console.log("a = " + a);
        console.log(typeof a)

        //最终状态:
        a = 1 + +"2" + 3;
        console.log("a = " + a);
        console.log(typeof a)

    </script>
</head>
<body>
    
</body>
</html>

image-20211105230709777