Open In App

JavaScript Int16Array from() Method

Last Updated : 11 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Int16Array array represents an array of twos-complement of 16-bit signed integers. By default, the contents of Int16Array are initialized to 0. 

The Int16Array.from() function is used to create a new Int16Array from an array-like or iterable object. So when you want to convert an arrayLike or iterable object to Int16Array then you can use this function by passing the object as a parameter to this function along with the map function and value used for the map function if needed.

 Syntax:  

Int16Array.from(source, mapFn, thisArg)

Parameters:

This method accepts three parameters that are specified below:  

  • source: This parameter is an array-like or iterable object which is used to convert to an Int16Array object.
  • mapFn: This parameter is Optional which is a Map function to call on every element of the Int16Array.
  • thisArg: This parameter is Optional which is a value to use as this when executing mapFn.

Return Value:

This method returns a new Int16Array instance.

JavaScript programs to Illustrate the working of from() function:

Example 1: In this example, we will see the basic use of the JavaScript Int16Array.from() method to create a new array from the string of numbers.

javascript




// Create a Int16Array from
// a string like structure
let array = Int16Array.from('654456543456');
 
// Display the result
console.log(array);


Output

Int16Array(12) [
  6, 5, 4, 4, 5,
  6, 5, 4, 3, 4,
  5, 6
]


Example 2: In this example, we will see the basic use of the JavaScript Int16Array.from() method implementing transformation to every element.

javascript




// Create a Int16Array from a array by converting
// numbers twice the actual number
let array = Int16Array.from([32, 43, 41, 34], z => z * 2);
 
// Display the result
console.log(array);


Output

Int16Array(4) [ 64, 86, 82, 68 ]


References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from# 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads