JavaScript进阶

一、函数

1.函数

greetWorld(); // Output: Hello, World!function greetWorld() {console.log('Hello, World!');
}

Another way to define a function is to use a function expression. To define a function inside an expression, we can use the function keyword. In a function expression, the function name is usually omitted. A function with no name is called an anonymous function. A function expression is often stored in a variable in order to refer to it.

const plantNeedsWater = function(day) {if(day === 'Wednesday'){return true;} else {return false;}
};
console.log(plantNeedsWater('Tuesday'));

或者,你还可以用这样的形式:

const plantNeedsWater = (day) => {if (day === 'Wednesday') {return true;} else {return false;}
};

 而对于某些接受一个参数,返回一个值,能写成一行的函数,我们还能进一步简化:

const squareNum = (num) => {return num * num;
};

可以简化成:

const squareNum = num => num * num;
  • The parentheses around num have been removed, since it has a single parameter.
  • The curly braces { } have been removed since the function consists of a single-line block.
  • The return keyword has been removed since the function consists of a single-line block.

2.Default Parameters

function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'eggs'){console.log(`Remember to buy ${item1}`);console.log(`Remember to buy ${item2}`);console.log(`Remember to buy ${item3}`);
}makeShoppingList();

3.作用域

  • Scope refers to where variables can be accessed throughout the program, and is determined by where and how they are declared.
  • Blocks are statements that exist within curly braces {}.
  • Global scope refers to the context within which variables are accessible to every part of the program.
  • Global variables are variables that exist within global scope.
  • Block scope refers to the context within which variables are accessible only within the block they are defined.
  • Local variables are variables that exist within block scope.
  • Global namespace is the space in our code that contains globally scoped information.
  • Scope pollution is when too many variables exist in a namespace or variable names are reused.

二、数组

1.打印数组

js可以直接打印数组

let newYearsResolutions = ['Keep a journal', 'Take a falconry class', 'Learn to juggle'];console.log(newYearsResolutions);

返回数组长度:

const objectives = ['Learn a new language', 'Read 52 books', 'Run a marathon'];console.log(objectives.length);

3

2.添加元素和删除元素

在js里,数组的长度是可变的,我们可以直接用push向其中添加元素:

const chores = ['wash dishes', 'do laundry', 'take out trash'];chores.push('cook dinner', 'mop floor');console.log(chores);
[ 'wash dishes','do laundry','take out trash','cook dinner','mop floor' ]

.push() can take a single argument or multiple arguments separated by commas. 

显然我们也能用pop移除数组中的元素:

const chores = ['wash dishes', 'do laundry', 'take out trash', 'cook dinner', 'mop floor'];
chores.pop();
console.log(chores)
  • .pop() does not take any arguments, it simply removes the last element of newItemTracker.
  • .pop() returns the value of the last element.

3.添加和删除第一个元素

如果想删除数组中的第一个元素

const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];groceryList.shift();
console.log(groceryList);
[ 'bananas','coffee beans','brown rice','pasta','coconut oil','plantains' ]

在第一个位置添加元素:

groceryList.unshift('popcorn');

4.返回部分数组 

 The .slice() array method returns a shallow copy of all or part of an array without modifying the original. A shallow copy duplicates the contents of an object into a new instance by reference; which is why changes to the copy are not reflected in the original.

The returned array contains the element specified by the first argument and all subsequent elements up to, but not including, the element specified by the second argument.

array.slice(start, end);

If only one argument is specified, the returned array contains all elements from the start position to the end of the array.

array.slice(start);

If start and end values are not provided, the method will return a copy of the whole array

array.slice();

A negative index can be used, indicating an offset from the end of the sequence.

const weekDays = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday',
];const outOutOffice = weekDays.slice(-6, -3);console.log(outOutOffice);
// Output: ['Tuesday', 'Wednesday', 'Thursday']

5.find the index of a particular element

const numbers = [6, 12, 8, 10];
const indexOf12 = numbers.indexOf(12);console.log(indexOf12);
// Output: 1
const pizzaToppings = ['pepperoni', 'olives', 'mushrooms'];
const indexOfPineapple = pizzaToppings.indexOf('pineapple');console.log(indexOfPineapple);
// Output: -1

6.二维数组

const nestedArr = [[1], [2, 3]];console.log(nestedArr[1]); // Output: [2, 3]
console.log(nestedArr[1][0]); // Output: 2

7.review

  • Arrays are lists that store data in JavaScript.
  • Arrays are created with brackets [].
  • Each item inside of an array is at a numbered position, or index, starting at 0.
  • We can access one item in an array using its index, with syntax like: myArray[0].
  • We can also change an item in an array using its index, with syntax like myArray[0] = 'new string';
  • Arrays have a length property, which allows you to see how many items are in an array.
  • Arrays have their own methods, including .push() and .pop(), which add and remove items from an array, respectively.
  • Arrays have many methods that perform different tasks, such as .slice() and .shift(), you can find documentation at the Mozilla Developer Network website.
  • Some built-in methods are mutating, meaning the method will change the array, while others are not mutating. You can always check the documentation.
  • Variables that contain arrays can be declared with let or const. Even when declared with const, arrays are still mutable. However, a variable declared with const cannot be reassigned.
  • Arrays mutated inside of a function will keep that change even outside the function.
  • Arrays can be nested inside other arrays.
  • To access elements in nested arrays chain indices using bracket notation.

三、循环

1.for

for (let counter = 5; counter < 11; counter++) {console.log(counter);
} 

2.while

const cards = ['diamond', 'spade', 'heart', 'club'];// Write your code below
let currentCard;while (currentCard !== 'spade') {currentCard = cards[Math.floor(Math.random() * 4)];console.log(currentCard);
}

这段代码使用了while循环和Math.random()方法来实现一个纸牌游戏的模拟,游戏规则是从四个花色中随机抽取一张牌,直到抽到黑桃(spade)为止。

具体来说,该代码首先定义了一个包含四个花色的数组cards,然后使用while循环来不断随机抽取一张牌,直到抽到黑桃为止。循环体中,使用Math.random()方法和Math.floor()方法来生成一个0-3之间的随机整数,然后使用该随机整数作为索引从cards数组中获取一张随机的牌,将其赋值给currentCard变量,并使用console.log()方法将其输出。如果当前抽到的牌不是黑桃,则继续循环,否则跳出循环。

3.do while

let countString = '';
let i = 0;do {countString = countString + i;i++;
} while (i < 5);console.log(countString);

4.break

let countString = '';
let i = 0;do {countString = countString + i;i++;
} while (i < 5);console.log(countString);

Banana.
Banana.
Banana.
Orange you glad I broke out the loop!

5.review 

  • Loops perform repetitive actions so we don’t have to code that process manually every time.
  • How to write for loops with an iterator variable that increments or decrements
  • How to use a for loop to iterate through an array
  • A nested for loop is a loop inside another loop
  • while loops allow for different types of stopping conditions
  • Stopping conditions are crucial for avoiding infinite loops.
  • do...while loops run code at least once— only checking the stopping condition after the first execution
  • The break keyword allows programs to leave a loop during the execution of its block

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/12954.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Jenkins搭建最简教程

纠结了一小会儿&#xff0c;到底要不要写这个&#xff0c;最终还是决定简单记录一下&#xff0c;因为Jenkins搭建实在是太简单了&#xff0c;虽然也有坑&#xff0c;但是坑主要在找稳定的版本上。 先学一个简称&#xff0c;LTS (Long Term Support) 属实是长见识了&#xff0c…

docker 搭建jenkins

1、拉取镜像 docker pull jenkins/jenkins:2.4162、创建文件夹 mkdir -p /home/jenkins_mount chmod 777 /home/jenkins_mount3、运行并构建容器 docker run --restartalways -d -p 10240:8080 -p 10241:50000 -v /home/jenkins_mount:/var/jenkins_home -v /etc/localtime:…

如何选择台式还是便携式多参数水质检测仪呢

选择台式还是便携式多参数水质检测仪主要取决于具体的使用需求和场景。 1.便携式多参数水质检测仪适用于需要在不同地点进行水质检测的情况&#xff0c;例如户外采样、实地调查等。它具有小巧轻便的特点&#xff0c;方便携带和操作&#xff0c;适合需要频繁移动或需要灵活使用的…

【LeetCode】152.乘积最大子数组

题目 给你一个整数数组 nums &#xff0c;请你找出数组中乘积最大的非空连续子数组&#xff08;该子数组中至少包含一个数字&#xff09;&#xff0c;并返回该子数组所对应的乘积。 测试用例的答案是一个 32-位 整数。 子数组 是数组的连续子序列。 示例 1: 输入: nums […

前端框架学习-基础前后端分离

前端知识栈 前端三要素&#xff1a;HTML、CSS、JS HTML 是前端的一个结构层&#xff0c;HTML相当于一个房子的框架&#xff0c;可类比于毛坯房只有一个结构。CSS 是前端的一个样式层&#xff0c;有了CSS的装饰&#xff0c;相当于房子有了装修。JS 是前端的一个行为层&#xff…

如何维护你的电脑:提升性能和延长使用寿命

如何维护你的电脑&#xff1a;提升性能和延长使用寿命 &#x1f607;博主简介&#xff1a;我是一名正在攻读研究生学位的人工智能专业学生&#xff0c;我可以为计算机、人工智能相关本科生和研究生提供排忧解惑的服务。如果您有任何问题或困惑&#xff0c;欢迎随时来交流哦&…

AWVS 15.6 使用教程

目录 介绍 版本 AWVS具有以下特点和功能&#xff1a; 功能介绍&#xff1a; Dashboard功能&#xff1a; Targets功能&#xff1a; Scans功能&#xff1a; Vulnerabilities功能&#xff1a; Reports功能&#xff1a; Users功能&#xff1a; Scan Profiles功能&#x…

webpack中文文档

基本安装 首先我们创建一个目录&#xff0c;初始化 npm&#xff0c;然后 在本地安装 webpack&#xff0c;接着安装 webpack-cli&#xff08;此工具用于在命令行中运行 webpack&#xff09;&#xff1a; mkdir webpack-demo cd webpack-demo npm init -y npm install webpack …

2023 年牛客多校第四场题解

A Bobo String Construction 题意&#xff1a;给定一个 01 01 01 字符串 t t t&#xff0c;构造一个长度为 n n n 的 01 01 01 串 s s s&#xff0c;使得 t t t 在 c o n c a t ( t , s , t ) {\rm concat}(t, s, t) concat(t,s,t) 中仅出现两次。多测&#xff0c; 1 ≤…

【数据结构】实验十二:图 查找

实验十二 图查找 一、实验目的与要求 1&#xff09;掌握拓扑排序的应用&#xff1b; 2&#xff09;掌握查找的概念和算法&#xff1b; 3&#xff09;掌握查找的基本原理以及各种算法的实现&#xff1b; 4&#xff09;掌握查找的应用。 二、实验内容 1. 用邻接表建立一…

WIZnet W51000S-EVB-PICO 入门教程(一)

概述 W5100S-EVB-Pico是基于树莓派RP2040和全硬件TCP/IP协议栈控制器W5100S的微控制器开发板-基本上与树莓派Pico板相同&#xff0c;但通过W5100S芯片增加了以太网功能。 W5100S-EVB-Pico特点 RP2040规格参数 双核Arm Cortex-M0 133MHz264KB 高速SRAM和2MB板载内存通过…

JAVA基础-多线程入门(详解)

目录 引言 一&#xff0c;线程概念 二&#xff0c;创建线程 2.1&#xff0c;继承Thread类&#xff0c;重写run方法 2.2&#xff0c;实现Runnable接口&#xff0c;重写run方法&#xff0c;实现Runnable接口的实现类的实例对象作为Thread构造函 数的target 2.3&#xff0c;通…

RCU 使用及机制源码的一些分析

》内核新视界文章汇总《 文章目录 1 介绍2 使用方法2.1 经典 RCU2.2 不可抢占RCU2.3 加速版不可抢占RCU2.4 链表操作的RCU版本2.5 slab 缓存支持RCU 3 源码与实现机制的简单分析3.1 数据结构3.2 不可抢占RCU3.3 加速版不可抢占RCU3.4 可抢占RCU3.5 报告禁止状态3.6 宽限期的开…

教雅川学缠论03-分型

原著作者将K线走势分成四中类型&#xff0c;这四中类型&#xff0c;就叫做分型&#xff0c;注意&#xff0c;分型是K线的组合&#xff08;至少3个K线&#xff09;&#xff0c;如下 下面我们以2023年7月武汉控股日K示例 四个分型用图来表示的话&#xff0c;还是很简单的&…

ubuntu安装ros以及安装遇到问题都可以解决

用ros的时候有天手贱&#xff0c;本来ros用的好好的又想着安装个anaconda 玩玩&#xff0c;结果好了&#xff0c;他两不能共存&#xff0c;于是我的ros环境就出问题了。roscore都跑步其来&#xff0c;只能卸载重装了。可卸载重装又出依赖问题了&#xff1a; 错误&#xff1a; …

spring5源码篇(13)——spring mvc无xml整合tomcat与父子容器的启动

spring-framework 版本&#xff1a;v5.3.19 文章目录 整合步骤实现原理ServletContainerInitializer与WebApplicationInitializer父容器的启动子容器的启动 相关面试题 整合步骤 试想这么一个场景。只用 spring mvc&#xff08;确切来说是spring-framework&#xff09;&#x…

Flink集群运行模式--Standalone运行模式

Flink集群运行模式--Standalone运行模式 一、实验目的二、实验内容三、实验原理四、实验环境五、实验步骤5.1 部署模式5.1.1 会话模式&#xff08;Session Mode&#xff09;5.1.2 单作业模式&#xff08;Per-Job Mode&#xff09;5.1.3 应用模式&#xff08;Application Mode&a…

从头开始:数据结构和算法入门(时间复杂度、空间复杂度)

目录 文章目录 前言 1.算法效率 1.1 如何衡量一个算法的好坏 1.2 算法的复杂度 2.时间复杂度 2.1 时间复杂度的概念 2.2 大O的渐进表示法 2.3常见时间复杂度计算 3.空间复杂度 4.常见复杂度对比 总结 前言 C语言的学习篇已经结束&#xff0c;今天开启新的篇章——数据结构和算…

gitee 配置ssh 公钥(私钥)

步骤1&#xff1a;添加/生成SSH公钥&#xff0c;码云提供了基于SSH协议的Git服务&#xff0c;在使用SSH协议访问项目仓库之前&#xff0c;需要先配置好账户/项目的SSH公钥。 绑定账户邮箱&#xff1a; git config --global user.name "Your Name" git config --glob…

【图像去噪】基于进化算法——自组织迁移算法(SOMA)的图像去噪研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…