function whatTheHeck(obj){
var arr = []
for(o in obj){
arr.concat(["what"])
}
return arr
}
whatTheHeck({"one":1, "two": 2})
The concat function completely fails to do anything. But if I put a breakpoint on that line in Firebug and run the line as a watch it works fine. And the for loop iterates twice but in the end arr still equals [].
To return an empty array from a function, we can create a new array with a zero size. In the example below, we create a function returnEmptyArray() that returns an array of int . We return new int[0] that is an empty array of int . In the output, we can get the length of the array getEmptyArray .
4 Ways to Empty an Array in JavaScript.
Because Array is type of object , the fact that an empty Array is conversed to true is correct.
Array.concat
creates a new array - it does not modify the original so your current code is actually doing nothing. It does not modify arr
.
So, you need to change your function to this to see it actually work:
function whatTheHeck(obj){
var arr = [];
for(o in obj){
arr = arr.concat(["what"]);
}
return arr;
}
whatTheHeck({"one":1, "two": 2});
If you're trying to just add a single item onto the end of the array, .push()
is a much better way:
function whatTheHeck(obj){
var arr = [];
for(o in obj){
arr.push("what");
}
return arr;
}
whatTheHeck({"one":1, "two": 2});
This is one of the things I find a bit confusing about the Javascript array methods. Some modify the original array, some do not and there is no naming convention to know which do and which don't. You just have to read and learn which work which way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With