最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript, how can this function possibly return an empty array? - Stack Overflow

matteradmin16PV0评论
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
  • Actually even without the loop it still fails. The only thing that works is to say straight return [].concat(["what"]). Something is very wrong with the world. – Moss Commented Nov 1, 2011 at 5:56
Add a comment  | 

1 Answer 1

Reset to default 47

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.

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far