admin管理员组文章数量:1431918
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 [].
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 [].
Share Improve this question asked Nov 1, 2011 at 5:53 MossMoss 3,8037 gold badges44 silver badges61 bronze badges 1 |1 Answer
Reset to default 47Array.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.
本文标签: javascripthow can this function possibly return an empty arrayStack Overflow
版权声明:本文标题:javascript, how can this function possibly return an empty array? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737600460a1998295.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
return [].concat(["what"])
. Something is very wrong with the world. – Moss Commented Nov 1, 2011 at 5:56