一、函数
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
我们还可以用这种语法来访问数组:
['A', 'B', 'C'][0]; // Returns 'A'
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 ofnewItemTracker
..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
orconst
. Even when declared withconst
, arrays are still mutable. However, a variable declared withconst
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