I have two JS scripts but neither of them does what I want to see.
I tried Firefox, Chrome and Internet Explorer. All the same.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="demo1">123</p>
<p id="demo2">456</p>
<script src="script.js"></script>
</body>
</html>
JS - script 1
function arrEmpty(arr){
arr.splice(0, arr.length);
return arr;
}
const arrEle = [1,2,3,4,5];
const result = arrEmpty(arrEle);
document.getElementById("demo1").innerHTML = arrEle.toString();
document.getElementById("demo2").innerHTML = result.toString();
Expected Result:
[1,2,3,4,5]
Result - Empty arrays in both lines:
JS - script 2
function arrEmpty(arr){
arr.length = 0;
return arr;
}
const arrEle = [1,2,3,4,5];
const result = arrEmpty(arrEle);
document.getElementById("demo1").innerHTML = arrEle.toString();
document.getElementById("demo2").innerHTML = result.toString();
Expected Result:
[1,2,3,4,5]
Result - Empty arrays in both lines:
Why is it that?
It works only if I swap the line before the function.
JS - script Modified:
function arrEmpty(arr){
arr.length = 0;
return arr;
}
const arrEle = [1,2,3,4,5];
document.getElementById("demo1").innerHTML = arrEle.toString();
const result = arrEmpty(arrEle);
document.getElementById("demo2").innerHTML = result.toString();