2018-10-10 22:03:03 +00:00
|
|
|
|
---
|
|
|
|
|
id: 56bbb991ad1ed5201cd392cb
|
2021-03-15 03:20:39 +00:00
|
|
|
|
title: 使用 push() 操作数组
|
2018-10-10 22:03:03 +00:00
|
|
|
|
challengeType: 1
|
2020-04-29 10:29:13 +00:00
|
|
|
|
videoUrl: 'https://scrimba.com/c/cnqmVtJ'
|
|
|
|
|
forumTopicId: 18237
|
2021-01-13 02:31:00 +00:00
|
|
|
|
dashedName: manipulate-arrays-with-push
|
2018-10-10 22:03:03 +00:00
|
|
|
|
---
|
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --description--
|
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
一个将数据添加到数组末尾的简单方法是 `push()` 函数。
|
2020-12-16 07:37:30 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
`.push()` 接受一个或多个参数(<dfn>parameters</dfn>),并把它压入到数组的末尾。
|
2021-02-06 04:42:36 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
示例:
|
2020-04-29 10:29:13 +00:00
|
|
|
|
|
|
|
|
|
```js
|
2021-02-06 04:42:36 +00:00
|
|
|
|
var arr1 = [1,2,3];
|
|
|
|
|
arr1.push(4);
|
|
|
|
|
|
|
|
|
|
var arr2 = ["Stimpson", "J", "cat"];
|
|
|
|
|
arr2.push(["happy", "joy"]);
|
2020-04-29 10:29:13 +00:00
|
|
|
|
```
|
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
`arr1` 现在值为 `[1, 2, 3, 4]`,`arr2` 值为 `["Stimpson", "J", "cat", ["happy", "joy"]]`。
|
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --instructions--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
把`["dog", 3]` 压入到 `myArray` 变量的末尾。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --hints--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
`myArray` 现在应该等于 `[["John", 23], ["cat", 2], ["dog", 3]]`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
|
assert(
|
|
|
|
|
(function (d) {
|
|
|
|
|
if (
|
|
|
|
|
d[2] != undefined &&
|
|
|
|
|
d[0][0] == 'John' &&
|
|
|
|
|
d[0][1] === 23 &&
|
|
|
|
|
d[2][0] == 'dog' &&
|
|
|
|
|
d[2][1] === 3 &&
|
|
|
|
|
d[2].length == 2
|
|
|
|
|
) {
|
|
|
|
|
return true;
|
|
|
|
|
} else {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
})(myArray)
|
|
|
|
|
);
|
2018-10-10 22:03:03 +00:00
|
|
|
|
```
|
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
|
# --seed--
|
|
|
|
|
|
|
|
|
|
## --after-user-code--
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
(function(z){return 'myArray = ' + JSON.stringify(z);})(myArray);
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
// Setup
|
|
|
|
|
var myArray = [["John", 23], ["cat", 2]];
|
|
|
|
|
|
|
|
|
|
// Only change code below this line
|
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --solutions--
|
2020-04-29 10:29:13 +00:00
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
|
```js
|
|
|
|
|
var myArray = [["John", 23], ["cat", 2]];
|
|
|
|
|
myArray.push(["dog",3]);
|
|
|
|
|
```
|