Notes on the third day of JavaScript basics

Notes on the third day of JavaScript basics

The difference between if multi-branch statement and switch:

  1. common ground

    • Can realize multi-branch selection, multiple choice 1
    • Interchangeable in most cases
  2. the difference:

    • The switch...case statement usually handles the situation 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).
    • The switch statement performs judgment and then directly executes the statement of the program, which is more efficient. The if...else statement has several judgment conditions, and it must be judged as many times as possible.
    • Switch must be === congruent, pay attention to the data type, and pay attention to break otherwise there will be penetration effects.
    • in conclusion:
      • When there are relatively few branches, if...else statements execute efficiently.
      • When there are many branches, the switch statement has high execution efficiency and a clearer structure.

for statement

Master the for loop statement to make the program capable of repeated execution

foris another loop control statement provided by JavaScript. It is whileonly different in syntax.

Basic usage of 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. Variations are the same as infinite loops, and forloops are whilethe same. If the increment and termination conditions are not set appropriately, an infinite loop will occur.

  2. Breaking out and terminating loops

<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 implement loop control, but no matter which statement is used, it is inseparable from the three characteristics of loops, namely the starting value, variation, and termination condition. As a beginner, you should focus on understanding these three characteristics. It is not necessary to Too much confusion about the difference between the three statements.
  • The starting value, change amount, and termination condition are designed by the developer based on logical needs to avoid the occurrence of infinite loops.
  • When the number of loops is clear, it is recommended to use forloops. When the number of loops is not clear, it is recommended to use whileloops.

Note: forThe grammatical structure is simpler, so forloops are used more frequently.

Nested loops

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

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

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

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

// 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>')
}

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

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(`
		<div> ${
      
      j} x ${
      
      i} = ${
      
      j * i} </div>
     `)
    }
    document.write('<br>')
}

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

array

Know what an array is and its application scenarios, and master the syntax of array declaration and access.

What is an array?

Array: (Array) is a data type that can store data in order

**Usage scenario:** If there is multiple data, it can be saved in an array and then placed in a variable. Management is very convenient.

Basic usage of arrays

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

  // 2. 定义非空数组
  let classes = ['小明', '小刚', '小红', '小丽', '小米']
</script>

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

Access arrays and array indexes

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 you can easily access the data units in the array 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 according to the position of the data units in the array. Note that they 0start from , as shown in the following figure:

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

Observe the above figure. The index value corresponding to the data unit [Xiao Ming] is [0], and the index value corresponding to the data unit [Xiao Hong] 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 unit value type

An array is a collection of data, and its unit 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 attribute

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

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

Operate array

As an object data type, arrays not only have lengthproperties that can be used, but also provide many methods:

  1. push dynamically adds a cell to the end of the array
  2. unshit dynamically adds a cell to the head of the array
  3. pop deletes the last cell
  4. shift deletes the first cell
  5. splice dynamically deletes any unit

When using the above four methods, operations are performed directly on the original array. That is, if any method is successfully called, the original array will be changed accordingly. lengthAnd there is no confusion when adding or removing cells .

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

Statefully add a cell to the head of the array
arr.unshift('VS Code')
console.log(arr)

// 3. splice dynamically deletes any unit
arr.splice(2, 1) // Delete 1 unit starting from the position with index value 2 console.log
(arr)

// 4. pop deletes the last unit
arr.pop()
console.log(arr)

// 5. shift deletes the first unit
arr.shift()
console.log(arr)


Guess you like

Origin blog.csdn.net/upgrade_bro/article/details/133280566