JavaScript arrayBuffer.slice() method


The JavaScript arrayBuffer.slice() method returns a new arrayBuffer whose contents are copy of the another arrayBuffer from begin, inclusive till end, exclusive.

Following is the code for the arrayBuffer.slice() method −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample,
.result {
      font-size: 18px;
      font-weight: 500;
      color: red;
}
.result {
   color: black;
}
</style>
</head>
<body>
<h1>JavaScript arrayBuffer.slice() property</h1>
<div class="sample">Original array buffer:</div>
<div class="result">Sliced array buffer:</div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to slice the array buffer to make its copy
</h3>
<script>
let resultEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
const buffer = new ArrayBuffer(16);
const int32View = new Int32Array(buffer);
int32View[0] = 11;
int32View[1] = 22;
int32View[2] = 33;
int32View.forEach((item) => {
   sampleEle.innerHTML += item + " , ";
});
const slicedBuffer = new Int32Array(buffer.slice(0, 8));
document.querySelector(".Btn").addEventListener("click", () => {
   slicedBuffer.forEach((item) => {
      resultEle.innerHTML += item + " , ";
   });
});
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −

Updated on: 06-May-2020

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements