Open In App

JavaScript Uint8ClampedArray.from() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The Uint8ClampedArray represents an array of 8-bit unsigned integers clamped to 0-255. If a value is specified that is not in the range of [0, 255], 0, or 255 will be set instead; if the specified value is not an integer, the nearest integer will be set. By default, the contents of Uint8ClampedArray are initialized to 0. 

The Uint8ClampedArray.from() method is used to create a new Uint8ClampedArray from an array-like or iterable object. So when you want to convert an arrayLike or iterable object to Uint8ClampedArray 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: 

Uint8ClampedArray.from( source, mapFn, thisArg )

Parameters:

This method accepts three parameters as mentioned above and described below:

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

Return Value:

This method returns a new Uint8ClampedArray instance. 

Below examples Illustrate the working of Uint8ClampedArray.from() method in JavaScript:

Example 1:

In this example, we will create an array form string using JavaScript Uint8ClampedArray.from() Method.

Javascript




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


Output

Uint8ClampedArray(8) [
  5, 4, 3, 2,
  3, 4, 2, 3
]

Example 2:

In this example, we will see the basic use of JavaScript Uint8ClampedArray.from() Method applying the transformation to each element.

javascript




// Create a Uint8ClampedArray from
// an array by adding 32 to each
// number using function
let  array = Uint8ClampedArray.from(
    [229, 213, 200, 201, 204], z => z  + 32);
 
// Display the result
console.log(array);


Output

Uint8ClampedArray(5) [ 255, 245, 232, 233, 236 ]

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


Last Updated : 11 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads