JavaScript Array.valueOf() Method
-
Syntax of JavaScript
array.valueOf()
: -
Example Code: Use the
array.valueOf()
Method to Convert an Array Object Into an Array -
Example Code: Use the
array.valueOf()
Method to Display the Array Object as HTML Text
The array.valueOf()
method returns the elements of an array object. When an array contains the elements of another array, the array.valueOf()
method will flatten the contents.
Syntax of JavaScript array.valueOf()
:
array.valueOf();
Parameter
This method does not take any parameters.
Return
This method returns the primitive value of an array after converting an array object.
Example Code: Use the array.valueOf()
Method to Convert an Array Object Into an Array
In JavaScript, we can use the array.valueOf()
method to get the actual elements of an array object. In this example, we created an array and an array object.
Using the new Array()
constructor, we have added arr1
to the array object. To get the primitive value of the array object, we used the array.valueOf()
method.
let arr1 = ["JavaScript","Array","Object"];
let arrObj = new Array(arr1);
let refValue = arrObj.valueOf();
console.log(arrObj);
Output:
[ [ 'JavaScript', 'Array', 'Object' ] ]
Example Code: Use the array.valueOf()
Method to Display the Array Object as HTML Text
We can’t use the array object to display text with JavaScript code. However, using array.valueOf()
method, we can display the elements of the array object as HTML text.
In this example, we created an array object. We will use the array.valueOf()
method to make an array object displayed as HTML text.
<html>
<body>
<div id="output"> </div>
<script>
let output = document.getElementById("output");
let array = new Array("File","Document");
let arr = array.valueOf();
console.log(arr);
output.innerHTML = arr;
</script>
</body>
</html>
Output:
File,Document
The array.valueOf()
method is supported in most browsers. Using this method, we can display the elements of an array object as HTML text.