# 章序号/节序号/节/笔记序号
codecademy,array
# 概念阐释
- 通过函数中的步骤来改变函数外部的**数组**变量中的值
- 调用函数时,变量名可以作为实参数
# 举例子
```js
const flowers = ['peony', 'daffodil', 'marigold'];
function addFlower(arr) {
return arr.push('lily');
}
addFlower(flowers); //调用函数
console.log(flowers);
// Output: ['peony', 'daffodil', 'marigold', 'lily']
```
- **`flowers` 数组有3个元素**。
- **function的行参是arr,在function body里添加lily到 `arr`行参数中。**
- **调用函数,实参数为`flower`变量。**
- **用`console.log()`发现数组发上了变异。****
# 类比、比较与对比
# 问题
🌟🌟🌟
```js
const concept = ['arrays', 'can', 'be', 'mutated'];
```
- 用函数`changeArr(arr)`修改mutated为MUTATED。
- 用函数`removeElement(newArr)`移除结尾的mutated。
#### 参考步骤
**1.**
In **main.js**, there is an array `concept`. There is also a function `changeArr` that will assign the element in index `3` of an array to `'MUTATED'`. The function `changeArr` was called with an argument of `concept`.
Underneath the function call, log `concept` to the console to check if this reassignment mutated the array.
**2.**
Let’s double check what happens if we mutate an array using a built-in method inside a function.
Under the `console.log()` statement, define another function named `removeElement` that takes a parameter of `newArr`. Inside the function body call `.pop()` on `newArr`.
**3.**
Call `removeElement()` with an argument of `concept`.
**4.**
After calling `removeElement(concept)`, check the value of `concept` by logging it to console.
Notice that in both cases, the change to the array was maintained outside of the function!
# 问题答案
```js
const concept = ['arrays', 'can', 'be', 'mutated'];
function changeArr(arr){
arr[3]='MUTATED';
//另一种写法:arr[3]=arr[3].toUpperCase();
return arr;
}
console.log(changeArr(concept));// Output:[ 'arrays', 'can', 'be', 'MUTATED' ]
//数组的写法:
// concept[3]='MUTATED';
// console.log(concept);
```
- 把arr想象成concept变量,其实就和**修改数组**一样了,容易理解
- 注意return那里是要返回什么?调用结果只是最后修改的元素,则 **`return arr[3]='MUTATED'`**
- 但如果是**修改**数组,仿照数组的写法: **`concept[3]='MUTATED';console.log(concept);`** 应该返回的是
**`return arr;`**
```js
function removeElement(newArr){
newArr.pop();
return newArr;
}
console.log(removeElement(concept));
```
# 备注(经验集/错误集)
## 经验集
- *把行参想象成变量名来写就理解了*
## 错误集
## 参考资料