javascript,这个函数怎么可能返回一个空数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7962953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript, how can this function possibly return an empty array?
提问by Moss
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 [].
concat 函数完全无法做任何事情。但是,如果我在 Firebug 的那一行上放置一个断点并将该行作为监视运行,它就可以正常工作。for 循环迭代了两次,但最终 arr 仍然等于 []。
回答by jfriend00
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
.
Array.concat
创建一个新数组 - 它不会修改原始数组,因此您当前的代码实际上什么都不做。它不会修改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:
如果您只想在数组的末尾添加一个项目,这.push()
是一个更好的方法:
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.
这是我对 Javascript 数组方法感到有点困惑的事情之一。有些修改原始数组,有些不修改,并且没有命名约定来知道哪些可以做哪些不可以。你只需要阅读并学习哪种工作方式。