js 基础笔记 流程控制

112 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第16天,点击查看活动详情

if else

大部分语言,如果只有if,没有else,其实可以省略 { },当然不提倡这么写。

  if(true) console.log('xxx')

if else if else的使用

  • 使用querySelector查找到[name='password']所对应的元素
  • 通过addEventListener监听keyup(键盘抬起事件)
  • 获得password 输入框中的值,然后判断它的长度大于10为超级安全、大于6为中级安全,否则为不安全。
  • 最后通过innerHTML方法将msg_text显示到span标签中
<html>

<head></head>

<body>
    <input type="password" name="password">
    <span id="msg"></span>
    <script>
        document.querySelector("[name='password']").addEventListener("keyup", function () {
            let password = document.querySelector("[name='password']").value
            let msg_text;
            if (password.length > 10) {
                msg_text = "高级安全"
            } else if (password.length > 6 && password.length <= 10) {
                msg_text = "中级安全"
            } else {
                msg_text = "不安全"
            }
            document.querySelector('#msg').innerHTML = msg_text
        })
    </script>
</body>
</html>

三元表达式

如下 ? 就相当于if : 就相当于else

 let h = 2 ? 2 : 5
 console.log(h)

多层判断

当然,如果套的层数较多时,不推荐使用。它会让可读性更低。

let a = 2? (3?'我是三':'我不是'):5     // '我是三

三元表达式的应用

向页面添加一个div元素 image.png

  • document.createElement 用于创建元素
  • div.style 添加 div的样式,这里判断option参数中是否有值,用到了三元表达式
  • document.body.appendChild将div元素添加到body后
<html>
<head></head>
<body>
    <script>
        function div(option = {}) {
            let div = document.createElement("div")
            // 三元判断参数中是否有width
            div.style.width = option.width ? option.width : '100px'
            div.style.height = option.height ? option.height : '100px'
            div.style.backgroundColor = option.backgroundColor ? option.backgroundColor : 'red'
            // 向body后追加元素
            document.body.appendChild(div)
        }
        div()
    </script>
</body>
</html>

如果我们传递了参数就会按参数的内容创建div

 div({width:'300px',height:'500px',backgroundColor:'green'})

image.png

switch

程序会拿参数(name)与case中的表达式比对,break会终止。当所有case都不匹配,则会走default

        let name = "视频"
        switch (name) {
            case '产品':
                console.log('chanpin')
                break;
            case '视频':
                console.log('shipin')
                break
            default:
                console.log('end')
        }