Reputation: 15
function test(){
input = document.getElementById("input").value;
array = [];
result = array.push(input);
console.log(typeof(result)) //returns number
}
So when i tries to add the user input into an array it keeps returning numbers, did i do something wrong?
Upvotes: 1
Views: 589
Reputation: 575
You have done it the right way but you're not logging the right thing to the browser console. Try console.log(result)
instead.
Maybe you can try doing it like this and see the behavior. Hope it helps!
let btn = document.getElementById('btn');
btn.addEventListener('click', add);
function add() {
const array = [];
let val = document.getElementById('inp').value;
array.push(val);
console.log('The array is = ', array);
}
<div>
<button id="btn">add</button>
<input id="inp" type="text"/>
</div>
Upvotes: 0
Reputation: 865
You’re doing it right; you’re just logging the wrong thing. Array.push mutates the array by adding an element to it and returns the length of the array, not the array itself. You can get rid of the result
variable. After array.push(input)
, console.log(array)
should give you the result you want.
Upvotes: 0
Reputation: 1071
You were using typeof(result)
which returns the type of your variable result
. The type is your case number
.
To see what is inside of result
, simle use console.log(result);
.
More about the typeof operator
Upvotes: 0