array.md 16.1 KB
Newer Older
D
DCloud_LXH 已提交
1 2 3 4
# Array

Array 对象是用于构造数组的全局对象,数组是类似于列表的高阶对象。

杜庆泉's avatar
杜庆泉 已提交
5 6
## 构造函数

7 8 9 10 11 12 13 14 15 16 17 18
### Constructor(arrayLength?)

<!-- UTSJSON.Array.Constructor.description -->

<!-- UTSJSON.Array.Constructor.param -->

<!-- UTSJSON.Array.Constructor.returnValue -->

<!-- UTSJSON.Array.Constructor.compatibility -->

<!-- UTSJSON.Array.Constructor.tutorial -->

杜庆泉's avatar
杜庆泉 已提交
19
### Constructor(arrayLength)
20 21 22 23 24 25 26 27

<!-- UTSJSON.Array.Constructor_1.description -->

<!-- UTSJSON.Array.Constructor_1.param -->

<!-- UTSJSON.Array.Constructor_1.returnValue -->

<!-- UTSJSON.Array.Constructor_1.compatibility -->
D
DCloud_LXH 已提交
28

29 30
<!-- UTSJSON.Array.Constructor_1.tutorial -->

杜庆泉's avatar
杜庆泉 已提交
31
### Constructor(...items)
32 33 34 35 36 37 38 39 40 41 42 43 44

<!-- UTSJSON.Array.Constructor_2.description -->

<!-- UTSJSON.Array.Constructor_2.param -->

<!-- UTSJSON.Array.Constructor_2.returnValue -->

<!-- UTSJSON.Array.Constructor_2.compatibility -->

<!-- UTSJSON.Array.Constructor_2.tutorial -->


## 实例属性
D
DCloud_LXH 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184

### length

<!-- UTSJSON.Array.length.description -->

<!-- UTSJSON.Array.length.param -->

<!-- UTSJSON.Array.length.returnValue -->

```ts
const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
console.log(clothing.length);
// expected output: 4
```

<!-- UTSJSON.Array.length.compatibility -->

边界情况说明:

- 在不同平台上,数组的长度限制不同,超出限制会导致相应的错误或异常
  * 编译至 JavaScript 平台时,最大长度为 2^32 - 1,超出限制会报错:`Invalid array length`
  * 编译至 Kotlin 平台时,最大长度受系统内存的限制,超出限制报错:`java.lang.OutOfMemoryError: Failed to allocate a allocation until OOM`
  * 编译至 Swift 平台时,最大长度也受系统内存的限制,目前超出限制没有返回信息。


## 实例方法


### find(predicate, thisArg?)

<!-- UTSJSON.Array.find.description -->

<!-- UTSJSON.Array.find.param -->

<!-- UTSJSON.Array.find.returnValue -->

```ts
const array1 = [5, 12, 8, 130, 44];

const found = array1.find((element:number):boolean => element > 10);

console.log(found);
// expected output: 12

```

<!-- UTSJSON.Array.find.compatibility -->

### findIndex(predicate, thisArg?)

<!-- UTSJSON.Array.findIndex.description -->

<!-- UTSJSON.Array.findIndex.param -->

<!-- UTSJSON.Array.findIndex.returnValue -->

```ts
const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element:number):boolean => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

```

<!-- UTSJSON.Array.findIndex.compatibility -->

### fill(value, start?, end?)

<!-- UTSJSON.Array.fill.description -->

<!-- UTSJSON.Array.fill.param -->

<!-- UTSJSON.Array.fill.returnValue -->

```ts
const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

```

<!-- UTSJSON.Array.fill.compatibility -->

### copyWithin(target, start?, end?)

<!-- UTSJSON.Array.copyWithin.description -->

<!-- UTSJSON.Array.copyWithin.param -->

<!-- UTSJSON.Array.copyWithin.returnValue -->

```ts
const array1 = ['a', 'b', 'c', 'd', 'e'];
// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]
// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]
```

<!-- UTSJSON.Array.copyWithin.compatibility -->

### pop()

<!-- UTSJSON.Array.pop.description -->

<!-- UTSJSON.Array.pop.param -->

<!-- UTSJSON.Array.pop.returnValue -->

```ts
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]

```

<!-- UTSJSON.Array.pop.compatibility -->

D
DCloud_LXH 已提交
185
### push(...items)
D
DCloud_LXH 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

<!-- UTSJSON.Array.push.description -->

<!-- UTSJSON.Array.push.param -->

<!-- UTSJSON.Array.push.returnValue -->

```ts
const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

```

<!-- UTSJSON.Array.push.compatibility -->

D
DCloud_LXH 已提交
210
### concat(...items)
D
DCloud_LXH 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

<!-- UTSJSON.Array.concat.description -->

<!-- UTSJSON.Array.concat.param -->

<!-- UTSJSON.Array.concat.returnValue -->

```ts
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
```

<!-- UTSJSON.Array.concat.compatibility -->

D
DCloud_LXH 已提交
228
### concat(...items)
D
DCloud_LXH 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342

<!-- UTSJSON.Array.concat_1.description -->

<!-- UTSJSON.Array.concat_1.param -->

<!-- UTSJSON.Array.concat_1.returnValue -->

<!-- UTSJSON.Array.concat_1.compatibility -->

### join(separator?)

<!-- UTSJSON.Array.join.description -->

<!-- UTSJSON.Array.join.param -->

<!-- UTSJSON.Array.join.returnValue -->

```ts
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

```

<!-- UTSJSON.Array.join.compatibility -->

### reverse()

<!-- UTSJSON.Array.reverse.description -->

<!-- UTSJSON.Array.reverse.param -->

<!-- UTSJSON.Array.reverse.returnValue -->

<!-- UTSJSON.Array.reverse.compatibility -->

### shift()

<!-- UTSJSON.Array.shift.description -->

<!-- UTSJSON.Array.shift.param -->

<!-- UTSJSON.Array.shift.returnValue -->

```ts
const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

```

<!-- UTSJSON.Array.shift.compatibility -->

### slice(start?, end?)

<!-- UTSJSON.Array.slice.description -->

<!-- UTSJSON.Array.slice.param -->

<!-- UTSJSON.Array.slice.returnValue -->

```ts
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
```

<!-- UTSJSON.Array.slice.compatibility -->

### sort(compareFn?)

<!-- UTSJSON.Array.sort.description -->

<!-- UTSJSON.Array.sort.param -->

<!-- UTSJSON.Array.sort.returnValue -->

```ts
const array2 = [5, 1, 4, 2, 3];
array2.sort((a: number, b: number):number => a - b);
// expect(array2).toEqual([1, 2, 3, 4, 5]);
```

<!-- UTSJSON.Array.sort.compatibility -->

杜庆泉's avatar
杜庆泉 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
**平台差异性**

在android平台,一定不能忽略两个对比元素相等的场景,否则可能会出现`java.lang.IllegalArgumentException: Comparison method violates its general contract!‌`
```

a.sort((a, b) : number => {
  // 这里的判断不能省略
  if(a.compareTo(b) == 0){
    return 0
  }
  return a - b
})
```



D
DCloud_LXH 已提交
359
### splice(start, deleteCount, ...items)
D
DCloud_LXH 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

<!-- UTSJSON.Array.splice.description -->

<!-- UTSJSON.Array.splice.param -->

<!-- UTSJSON.Array.splice.returnValue -->

```ts
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
```

<!-- UTSJSON.Array.splice.compatibility -->

D
DCloud_LXH 已提交
382
### unshift(...items)
D
DCloud_LXH 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649

<!-- UTSJSON.Array.unshift.description -->

<!-- UTSJSON.Array.unshift.param -->

<!-- UTSJSON.Array.unshift.returnValue -->

```ts
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
```

<!-- UTSJSON.Array.unshift.compatibility -->

### indexOf(searchElement, fromIndex?)

<!-- UTSJSON.Array.indexOf.description -->

<!-- UTSJSON.Array.indexOf.param -->

<!-- UTSJSON.Array.indexOf.returnValue -->

```ts
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

```

<!-- UTSJSON.Array.indexOf.compatibility -->

### lastIndexOf(searchElement, fromIndex?)

<!-- UTSJSON.Array.lastIndexOf.description -->

<!-- UTSJSON.Array.lastIndexOf.param -->

<!-- UTSJSON.Array.lastIndexOf.returnValue -->

```ts
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// expected output: 3

console.log(animals.lastIndexOf('Tiger'));
// expected output: 1
```

<!-- UTSJSON.Array.lastIndexOf.compatibility -->

### every(predicate, thisArg?)

<!-- UTSJSON.Array.every.description -->

<!-- UTSJSON.Array.every.param -->

<!-- UTSJSON.Array.every.returnValue -->

```ts
const isBelowThreshold = (currentValue:number):boolean => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
```

<!-- UTSJSON.Array.every.compatibility -->

### some(predicate, thisArg?)

<!-- UTSJSON.Array.some.description -->

<!-- UTSJSON.Array.some.param -->

<!-- UTSJSON.Array.some.returnValue -->


```ts
const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element:number):boolean=> element % 2 == 0;

console.log(array.some(even));
// expected output: true
```

<!-- UTSJSON.Array.some.compatibility -->

### forEach(callbackfn, thisArg?)

<!-- UTSJSON.Array.forEach.description -->

<!-- UTSJSON.Array.forEach.param -->

<!-- UTSJSON.Array.forEach.returnValue -->

```ts
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
```

> 特别注意:
> 不可在 forEach 的 callbackFn 里添加或者删除原数组元素,此行为是危险的,在 Android 平台会造成闪退,在 iOS 平台会造成行为不符合预期。如果想实现该效果,请用 while 循环。

```ts

const array1 = ['a', 'b', 'c'];
array1.forEach(element => {
	console.log(element)
	array1.pop() // 此行为在 Android 平台会造成闪退,在 iOS 平台会输出 'a', 'b', 'c', 而 JS 会输出 'a', 'b'
});

// 如果想让上述行为正常运行,可以用 while 循环实现:

let array1 = ['a', 'b', 'c'];
let index = 0;
while (index < array1.length) {
  console.log(array1[index]);
  array1.pop();
  index += 1;
}

```

<!-- UTSJSON.Array.forEach.compatibility -->

### map(callbackfn, thisArg?)

<!-- UTSJSON.Array.map.description -->

<!-- UTSJSON.Array.map.param -->

<!-- UTSJSON.Array.map.returnValue -->

```ts
const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map((x:number):number => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

```

<!-- UTSJSON.Array.map.compatibility -->

### filter(predicate, thisArg?)

<!-- UTSJSON.Array.filter.description -->

<!-- UTSJSON.Array.filter.param -->

<!-- UTSJSON.Array.filter.returnValue -->

```ts
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word:string):boolean => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

```

<!-- UTSJSON.Array.filter.compatibility -->

### reduce(callbackfn)

<!-- UTSJSON.Array.reduce.description -->

<!-- UTSJSON.Array.reduce.param -->

<!-- UTSJSON.Array.reduce.returnValue -->

```ts
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue:number, currentValue:number):number => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

```

<!-- UTSJSON.Array.reduce.compatibility -->

### reduceRight(callbackfn)

<!-- UTSJSON.Array.reduceRight.description -->

<!-- UTSJSON.Array.reduceRight.param -->

<!-- UTSJSON.Array.reduceRight.returnValue -->

<!-- UTSJSON.Array.reduceRight.compatibility -->

### isArray(arg)

<!-- UTSJSON.Array.isArray.description -->

<!-- UTSJSON.Array.isArray.param -->

<!-- UTSJSON.Array.isArray.returnValue -->

```ts
console.log(Array.isArray([1, 3, 5]));
// Expected output: true

console.log(Array.isArray('[]'));
// Expected output: false

console.log(Array.isArray(new Array(5)));
// Expected output: true

console.log(Array.isArray(new Int16Array([15, 33])));
// Expected output: false
```

<!-- UTSJSON.Array.isArray.compatibility -->

### includes(searchElement, fromIndex?)

<!-- UTSJSON.Array.includes.description -->

<!-- UTSJSON.Array.includes.param -->

<!-- UTSJSON.Array.includes.returnValue -->

<!-- UTSJSON.Array.includes.compatibility -->

### toKotlinList()

<!-- UTSJSON.Array.toKotlinList.description -->

<!-- UTSJSON.Array.toKotlinList.param -->

<!-- UTSJSON.Array.toKotlinList.returnValue -->

<!-- UTSJSON.Array.toKotlinList.compatibility -->

<!-- UTSJSON.Array.toKotlinList.tutorial -->

<!-- UTSJSON.Array.tutorial -->

杜庆泉's avatar
杜庆泉 已提交
650 651


杜庆泉's avatar
杜庆泉 已提交
652
## Android 平台方法
杜庆泉's avatar
杜庆泉 已提交
653

杜庆泉's avatar
杜庆泉 已提交
654
* 目前 Array 类型编译到 `kotlin``io.dcloud.uts.UTSArray`, 该类继承自 `java.util.ArrayList`,所有`java` /`kotlin` 为其提供的扩展函数(如:`toTypedArray` 等),均可以正常调用。
杜庆泉's avatar
杜庆泉 已提交
655 656


D
DCloud_LXH 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
## 常见操作

- 创建数组
```ts
const fruits = ['Apple', 'Banana']
console.log(fruits.length)
```
- 通过索引访问数组元素
```ts
const first = fruits[0]
// Apple
const last = fruits[fruits.length - 1]
// Banana
```
- 遍历数组
```ts
fruits.forEach(function(item, index, array) {
  console.log(item, index)
})
// Apple 0
// Banana 1
```
- 注意:数组遍历不推荐使用 for in 语句,因为在 ts 中 for in 遍历的是数组的下标,而在 Swift 和 Kottlin 中遍历的是数组的元素,存在行为不一致。

- 添加元素到数组的末尾
```ts
const newLength = fruits.push('Orange')
// ["Apple", "Banana", "Orange"]
```
- 删除数组末尾的元素
```ts
const last = fruits.pop() // remove Orange (from the end)
// ["Apple", "Banana"]
```
- 删除数组头部元素
```ts
const first = fruits.shift() // remove Apple from the front
// ["Banana"]
```
- 添加元素到数组的头部
```ts
const newLength = fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"]
```
- 找出某个元素在数组中的索引
```ts
fruits.push('Mango')
// ["Strawberry", "Banana", "Mango"]
const pos = fruits.indexOf('Banana')
// 1
```
- 通过索引删除某个元素
```ts
const removedItem = fruits.splice(pos, 1) // this is how to remove an item
// ["Strawberry", "Mango"]
```
- 从一个索引位置删除多个元素
```ts
const vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']
console.log(vegetables)
// ["Cabbage", "Turnip", "Radish", "Carrot"]
const pos = 1
const n = 2
const removedItems = vegetables.splice(pos, n)
// this is how to remove items, n defines the number of items to be removed,
// starting at the index position specified by pos and progressing toward the end of array.
console.log(vegetables)
// ["Cabbage", "Carrot"] (the original array is changed)
console.log(removedItems)
// ["Turnip", "Radish"]
```
- 复制一个数组
```ts
const shallowCopy = fruits.slice() // this is how to make a copy
// ["Strawberry", "Mango"]
```
### 访问数组元素

数组的索引是从 0 开始的,第一个元素的索引为 0,最后一个元素的索引等于该数组的 长度 减 1。

如果指定的索引是一个无效值,将会抛出 IndexOutOfBoundsException 异常

下面的写法是错误的,运行时会抛出 SyntaxError 异常,而原因则是使用了非法的属性名:

```ts
console.log(arr.0) // a syntax error
```