JavaScript Basics - Day 3

JavaScript Basics - Day 3

The difference between if multi-branch statement and switch:

  1. common ground

    • Can achieve multi-branch selection, multi-choice 1
    • interchangeable in most cases
  2. the difference:

    • The switch...case statement usually deals with the case where the case is a relatively certain value , while the if...else... statement is more flexible and is usually used for range judgment (greater than, equal to a certain range).
    • It is more efficient to execute the statement of the program directly after the switch statement is judged, and if...else statement has several judgment conditions, how many times have to be judged
    • Switch must pay attention to must be === congruent, must pay attention to the data type, and pay attention to break at the same time, otherwise there will be a penetrating effect
    • in conclusion:
      • When there are fewer branches, the execution efficiency of the if...else statement is high.
      • When there are many branches, the execution efficiency of the switch statement is high, and the structure is clearer.

for statement

Master the for loop statement, so that the program has the ability to execute repeatedly

foris another loop control statement provided by JavaScript, and it differs whileonly in syntax from .

Basic use of the for statement

  1. 3 elements to achieve circulation
<script>
  // 1. 语法格式
  // for(起始值; 终止条件; 变化量) {
      
      
  //   // 要重复执行的代码
  // }

  // 2. 示例:在网页中输入标题标签
  // 起始值为 1
  // 变化量 i++
  // 终止条件 i <= 6
  for(let i = 1; i <= 6; i++) {
      
      
    document.write(`<h${ 
        i}>循环控制,即重复执行<h${ 
        i}>`)
  }
</script>
  1. The amount of change is the same as the infinite loop, and forthe loop is whilethe same as , if the increment and termination conditions are not set properly, an infinite loop will occur.

  2. Break out and terminate the loop

<script>
    // 1. continue 
    for (let i = 1; i <= 5; i++) {
      
      
        if (i === 3) {
      
      
            continue  // 结束本次循环,继续下一次循环
        }
        console.log(i)
    }
    // 2. break
    for (let i = 1; i <= 5; i++) {
      
      
        if (i === 3) {
      
      
            break  // 退出结束整个循环
        }
        console.log(i)
    }
</script>

in conclusion:

  • JavaScriptA variety of statements are provided to achieve loop control, but no matter which statement is used, it cannot be separated from the three characteristics of the loop, namely, the initial value, the amount of change, and the termination condition
  • The initial value, change amount, and termination condition are designed by the developer according to the logical needs to avoid the occurrence of an infinite loop.
  • It is recommended to use loops when the number of loops is specified , and it is recommended to use loops forwhen the number of loops is not clearwhile
  • Note: forThe grammatical structure of is more concise, so the frequency of use of forthe loop will be more.

iterate over the array

let arr = ['刘德华', '刘晓强', '刘晓庆', '刘若英', '刘热巴', 'pink老师']
for (let i = 0; i < arr.length; i++) {
      console.log(arr[i])
    }

loop nesting

Using the knowledge of circulation to compare a simple astronomical knowledge, we know that the earth is also revolving around the sun while it is rotating. If both rotation and revolution are regarded as cycles, it is equivalent to nesting another cycle within the cycle.

In fact, any loop statement in JavaScript supports the nesting of loops, as shown in the following code:

64791826139
// 1. 外面的循环 记录第n天 
for (let i = 1; i < 4; i++) {
    document.write(`第${i}天 <br>`)
    // 2. 里层的循环记录 几个单词
    for (let j = 1; j < 6; j++) {
        document.write(`记住第${j}个单词<br>`)
    }
}

Remember, the outer loop loops once, and the inner loop loops all

inverted triangle

 // 外层打印几行
for (let i = 1; i <= 5; i++) {
    
    
    // 里层打印几个星星
    for (let j = 1; j <= i; j++) {
    
    
        document.write('★')
    }
    document.write('<br>')
}

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-c0uIzArg-1680682058291)(assets/1647918678956.png)]

Nine nine multiplication table

style css

span {
    
    
    display: inline-block;
    width: 100px;
    padding: 5px 10px;
    border: 1px solid pink;
    margin: 2px;
    border-radius: 5px;
    box-shadow: 2px 2px 2px rgba(255, 192, 203, .4);
    background-color: rgba(255, 192, 203, .1);
    text-align: center;
    color: hotpink;
}

javascript

 // 外层打印几行
for (let i = 1; i <= 9; i++) {
    
    
    // 里层打印几个星星
    for (let j = 1; j <= i; j++) {
    
    
        // 只需要吧 ★ 换成  1 x 1 = 1   
        document.write(`
		<span> ${
      
      j} x ${
      
      i} = ${
      
      j * i} </span>
     `)
    }
    document.write('<br>')
}

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-pVKXt5gN-1680682058293)(assets/1647918734677.png)]

array

Introduction

Array: (Array) is a data type that can store data in sequence. Object-oriented type

**Usage scenario:** If there are multiple data can be stored in an array, and then placed in a variable, the management is very convenient

Basic use of arrays

Defining arrays and array cells

<script>
  // 1. 语法,使用 [] 来定义一个空数组
  // 定义一个空数组,然后赋值给变量 classes
  // let classes = [];

  // 2. 定义非空数组
  let classes = ['小明', '小刚', '小红', '小丽', '小米']
  //3.构造函数声明函数
  let arr = new Array(1,2,3,4)
  //4. 数组求和 与 平均值
  	for循环遍历数组  内部sum=sum+arr[i]
    平均值 sum/arr.length
  // 5. 求数组中的最大值
    数组遍历   三元运算表达式 代替if循环
</script>

By []defining an array, real data can be stored in the data, such as Xiaoming, Xiaogang, Xiaohong, etc. are all data in the array. These data are called array units, and the array units are separated by English commas.

Accessing arrays and array indices

Using an array to store data is not the ultimate goal, the key is to be able to access the data (units) in the array at any time. In fact, JavaScript numbers each data unit in the array, and the data unit in the array can be easily accessed through the number of the data unit in the array.

We call the number of the data unit in the array the index value, and some people call it the subscript.

The index values ​​are actually arranged in order according to the position of the data unit in the array, note that it 0starts from , as shown in the following figure:

array

Observing the above figure, the index value corresponding to the data unit [Xiaoming] is [0], and the index value corresponding to the data unit [Xiaohong] is [2]

<script>
  let classes = ['小明', '小刚', '小红', '小丽', '小米']
  
  // 1. 访问数组,语法格式为:变量名[索引值]
  document.write(classes[0]) // 结果为:小明
  document.write(classes[1]) // 结果为:小刚
  document.write(classes[4]) // 结果为:小米
  
  // 2. 通过索引值还可以为数组单重新赋值
  document.write(classes[3]) // 结果为:小丽
  // 重新为索引值为 3 的单元赋值
  classes[3] = '小小丽'
  document.wirte(classes[3]); // 结果为: 小小丽
</script>

data element value type

An array is a collection of data, and its cell values ​​can be of any data type

<script>
  // 6. 数组单值类型可以是任意数据类型

  // a) 数组单元值的类型为字符类型
  let list = ['HTML', 'CSS', 'JavaScript']
  // b) 数组单元值的类型为数值类型
  let scores = [78, 84, 70, 62, 75]
  // c) 混合多种类型
  let mixin = [true, 1, false, 'hello']
</script>

Array length property

Again, arrays are not a new data type in JavaScript, they are objects.

<script>
  // 定义一个数组
  let arr = ['html', 'css', 'javascript']
  // 数组对应着一个 length 属性,它的含义是获取数组的长度
  console.log(arr.length) // 3
</script>

Operate array

Array addition, deletion, modification and query

Modify the array: number [subscript] = new value and reassign

increase array

  1. push dynamically adds a unit to the end of the array
  2. unshift dynamically adds a cell to the head of the array

Delete array: array as object data type

  1. pop removes the last cell
  2. shift deletes the first cell
  3. splice dynamically deletes any unit arr.splice(starting position—index number, number of deleted elements)

When using the above 4 methods, all operations are performed directly on the original array, that is, if any method is successfully called, the original array will change accordingly. And there is lengthno .

<script>
  // 定义一个数组
  let arr = ['html', 'css', 'javascript']

  // 1. push 动态向数组的尾部添加一个单元
  arr.push('Nodejs')
  console.log(arr)
  arr.push('Vue')

  // 2. unshit 动态向数组头部添加一个单元
  arr.unshift('VS Code')
  console.log(arr)

  // 3. splice 动态删除任意单元
  arr.splice(2, 1) // 从索引值为2的位置开始删除1个单元
  console.log(arr)

  // 4. pop 删除最后一个单元
  arr.pop()
  console.log(arr)

  // 5. shift 删除第一个单元
  arr.shift()
  console.log(arr)
</script>

array filter

//筛选大于10 的 
</script>
    let arr = [2, 0, 6, 1, 77, 9, 54, 3, 78, 7]
    newarr = [];
    for(i=0;i<arr.length;i++){
    
    
      if(arr[i]>=10){
    
    
          newarr.push(arr[i]);
      }
    }
    console.log(newarr);
  </script>

array goes to 0

 <script>
    let arr = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7]
    // 1. 声明一个新的数组
    let newArr = []
    // 2. 遍历筛选
    for (let i = 0; i < arr.length; i++) {
    
    
      if (arr[i] !== 0) {
    
    
        newArr.push(arr[i])
      }
    }
    // 输出新数组
    console.log(newArr)    
  </script>

array sort

arr.sort()  // 排序  默认升序
//升序
arr.sort(function(a,b){
    
    
            return a-b
        })
//降序
arr.sort(function(a,b){
    
    
            return b-a
        })
//for 循环的冒泡

Comprehensive Case—Rendering Histogram

    <style>
        * {
      
      
            margin: 0;
            padding: 0;
        }

        .box {
      
      
            display: flex;
            width: 700px;
            height: 300px;
            border-left: 1px solid pink;
            border-bottom: 1px solid pink;
            margin: 50px auto;
            justify-content: space-around;
            align-items: flex-end;
            text-align: center;
        }

        .box>div {
      
      
            display: flex;
            width: 50px;
            background-color: pink;
            flex-direction: column;
            justify-content: space-between;
        }

        .box div span {
      
      

            margin-top: -20px;
        }

        .box div h4 {
      
      
            margin-bottom: -35px;
            width: 70px;
            margin-left: -10px;
        }
    </style>

    <script>
        let arr = []
        for (let i = 1; i <=4; i++) {
      
      
            arr.push( prompt(`输入第${ 
        i}季度营业额 单位千万`))
        }
        // console.log(arr);
        document.write(` <div class="box">`)
            for(let i = 0; i <4; i++){
      
      
                document.write(`
                            <div style="height: ${ 
        arr[i]}px;">
                                <span>${ 
        arr[i]}</span>
                                <h4>第${ 
        i + 1}季度</h4>
                            </div>          
                            `)
            }
        document.write(` </div>`)

    </script>

Bubble Sort

//冒泡
        for(let i= 0;i<arr.length-1;i++){
    
    
            for(let j= 0;j<arr.length-i-1;j++){
    
    
                if(arr[j]<arr[j+1]){
    
    
                     temp = arr[j+1]
                     arr[j+1] = arr[j]
                     arr[j] = temp
                }
            }  
        }

Guess you like

Origin blog.csdn.net/weixin_62643012/article/details/129972284