# 章序号/节序号/节/笔记序号 codecademy,array # 概念阐释 ## 语义 数组是一种特殊类型的[[JavaScript 变量|变量]],在使用一组相关联的数据时,使用数组是更好的办法,不要创建大量的变量。通常与[[js loops looping through Arrays 循环和数组|循环]]一起使用。 **任何数据类型**:一组变量中可以有多种[[JavaScript 数据类型|数据类型]],也可以是一种。 ```js let newYearsResolutions = ['Keep a journal', 'Take a falconry class', 'Learn to juggle']; let concepts = ['creating arrays', 10, true]; ``` ## 语法 ![Diagram outlining an array literal that has 3 separate elements, a comma separates each element (a string, a number, and a boolean) and the elements are wrapped with square brackets](https://content.codecademy.com/courses/learn-javascript-arrays/array%20literal.svg) - array使用`[]` 包含内容 - 每一个内容被称为**元素** - **元素**可以是不同的datatype,也可以是相同的 # 举例子 # 类比、比较与对比 ## 访问元素 - 数组中的元素,值的位置是固定的,被看作是**index索引** - 我们可以通过索引访问数组元素,索引从 `0` 开始而不是 `1` ![Diagram outlining how to access the property of an array using the index of the element](https://content.codecademy.com/courses/learn-javascript-arrays/array%20indices.svg) ### 通过index访问单个字符 ```js const hello = 'Hello World';//这是一个变量,不是数组 console.log(hello[6]);// Output: W ``` ## 替换元素 - 修改数组元素 ```js let seasons = ['Winter', 'Spring', 'Summer', 'Fall']; seasons[3] = 'Autumn';//替换fall to autumn console.log(seasons); //Output: ['Winter', 'Spring', 'Summer', 'Autumn'] ``` ## 变量关键字const和let - 变量const在一般概念下是不能被重新赋值的,但当变量中存储的是数组时,可以被重新赋值。 # 问题 🌟🌟🌟🌟🌟 1. 用函数加数组的方式计算面积和体积。 2. 随机访问Rock paper scissors,加入到函数当中 ```js computerChoice=['rock','paper','scissors']; ``` # 问题答案 1. 《js&jQuery》p85 ```js function calculate(width,length,high){ let area= width*length; let volume = width*length*high; let calculateArray = [area,volume];//数组内实则是变量所代表的数字数据类型 return calculateArray; } let area = calculate(2,5)[0]; let volume = calculate(2,5,10)[1]; console.log(area); console.log(volume); ``` 2. ```js //访问全部数组元素 console.log(computerChoice); //随机访问数组元素,[index]random访问] console.log(computerChoice[Math.floor(Math.random()*3)]); //加入函数 const getComputerChoice = () => { let computerChoice=['rock','paper','scissors']; return computerChoice[Math.floor(Math.random()*3)]; }; console.log(getComputerChoice()); ``` # 备注(经验集/错误集) ## 经验集 *从调用结果往回写,比较清楚怎么设计步骤。* ## 错误集 *没有写return,return你想要计算机返回的值,如果不写等于没有告诉计算机你想要它返回什么结果给你。* *在这道题中,你想要计算机返回**面积**和**体积**的值。* ## 参考资料 ## 归档 1. [做课后练习题](https://www.codecademy.com/courses/introduction-to-javascript/lessons/arrays/exercises/property-access) 2. 创建一个数组变量 3. 访问并print最后一个数组元素 ```js const famousSayings = ['Fortune favors the brave.', 'A joke is a very serious thing.', 'Where there is love there is life.']; ``` 4. update第一个数组元素为`avocados` ```js let groceryList = ['bread', 'tomatoes', 'milk']; ``` 5. 修改以下步骤 ```js let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha']; const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork']; ``` - 重新赋值condiments索引0**元素**为'Mayo'(update) - 重新赋值变量condiments为单一string`['Mayo']` - 重新赋值utensils最有一个元素为'Spoon' - 重新赋值变量utensils会怎样?