JavaScript Array Question 4

Introduction

What is the output of the following code.


let myNumArray = [1,2,3,4,5,6,7,8,9,10];

console.log( myNumArray.slice(3,6).toString());
console.log( myNumArray.slice(6).toString()); 
console.log( myNumArray.slice(-3).toString()); 

myNumArray = [1,2,3,4,5,6,7,8,9,10];//from w  ww  .  j  av a  2  s . c  om

myNumArray.splice(2,3);

console.log( myNumArray.toString());


myNumArray.splice(2,0, "hello", "world");

console.log( myNumArray.toString());


4,5,6
7,8,9,10
8,9,10
1,2,6,7,8,9,10
1,2,hello,world,6,7,8,9,10

Note

Code with comments.


// Array.slice examples:
// myNumArray will serve as an example for slice() and splice()
let myNumArray = [1,2,3,4,5,6,7,8,9,10];

console.log( myNumArray.slice(3,6).toString()); // 4,5,6
console.log( myNumArray.slice(6).toString()); // 7,8,9,10
console.log( myNumArray.slice(-3).toString()); // 8,9,10

// Lets reset our array
myNumArray = [1,2,3,4,5,6,7,8,9,10];/*from   w  w w  .  ja  v  a2s.com*/

// now lets just remove some from the middle (from position 2 to 5)
myNumArray.splice(2,3);

// see the result:
console.log( myNumArray.toString());
// 1,2,6,7,8,9,10

// Lets do that again, but just insert a bunch
myNumArray.splice(2,0, "hello", "world");

// Write out the result
console.log( myNumArray.toString());



PreviousNext

Related