|
| 1 | +functionrandomArray(length:number,start:number,end:number):number[]{ |
| 2 | +constarray:number[]=newArray(length); |
| 3 | +for(leti=0;i<length;i++){ |
| 4 | +array[i]=Math.floor(Math.random()*end)+start; |
| 5 | +} |
| 6 | +returnarray; |
| 7 | +} |
| 8 | + |
| 9 | +functionsumPositive(array:number[]):number{ |
| 10 | +letsum=0; |
| 11 | +array.forEach((element)=>{ |
| 12 | +if(element>0)sum+=element; |
| 13 | +}); |
| 14 | +returnsum; |
| 15 | +} |
| 16 | + |
| 17 | +functionproductElements(array:number[]):number{ |
| 18 | +letp=1; |
| 19 | +array.forEach((element)=>{ |
| 20 | +if(element!==0)p*=element; |
| 21 | +}); |
| 22 | +returnp; |
| 23 | +} |
| 24 | + |
| 25 | +functionrun():void{ |
| 26 | +console.log(' Array 07 tasks '); |
| 27 | + |
| 28 | +constmyArray:number[]=randomArray(7,-10,30); |
| 29 | +console.log('Array ',myArray); |
| 30 | +constsum=sumPositive(myArray); |
| 31 | +console.log(' Sum of positive elements: ',sum); |
| 32 | +constproduct=productElements(myArray); |
| 33 | +console.log(" Product of array's elements ",product); |
| 34 | +} |
| 35 | + |
| 36 | +exportdefaultrun; |
| 37 | + |
| 38 | +/*** |
| 39 | + * |
| 40 | +
|
| 41 | +### `push` Method: |
| 42 | +
|
| 43 | +The `push` method appends one or more elements to the end of an array |
| 44 | +and returns the new length of the array after the addition. |
| 45 | +
|
| 46 | +**Syntax:** |
| 47 | +```typescript |
| 48 | +array.push(element1, ..., elementN); |
| 49 | +``` |
| 50 | +
|
| 51 | +- `element1, ..., elementN`: The elements to add to the end of the array. |
| 52 | +
|
| 53 | +**Example:** |
| 54 | +```typescript |
| 55 | +let numbers: number[] = [1, 2, 3]; |
| 56 | +numbers.push(4, 5); |
| 57 | +console.log(numbers); // Output: [1, 2, 3, 4, 5] |
| 58 | +``` |
| 59 | +
|
| 60 | +### Benefits: |
| 61 | +
|
| 62 | +- **Mutates the Original Array:** Unlike methods that return a new array, |
| 63 | + such as `concat` or `slice`, `push` modifies the original array by adding |
| 64 | + elements to it directly. |
| 65 | +
|
| 66 | +- **Efficient Appending:** `push` is typically efficient for adding elements |
| 67 | + to the end of an array, especially when appending one element at a time. |
| 68 | +
|
| 69 | +- **Returns New Length:** The method returns the new length of the array after |
| 70 | + adding elements, which can be useful for tracking the array's size. |
| 71 | +
|
| 72 | +### Notes: |
| 73 | +
|
| 74 | +- You can pass one or more elements as arguments to `push`, and they will be |
| 75 | + added to the end of the array in the order they are passed. |
| 76 | +
|
| 77 | +- The `push` method mutates the original array and modifies its length. |
| 78 | +
|
| 79 | +- If you want to add elements to the beginning of an array, you can use the |
| 80 | + `unshift` method instead. |
| 81 | +***/ |