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

前端 未结 1 1041
离开以前
离开以前 2021-02-07 03:40
function whatTheHeck(obj){
  var arr = []

  for(o in obj){
    arr.concat([\"what\"])
  }

  return arr
}

whatTheHeck({\"one\":1, \"two\": 2})

The co

1条回答
  •  长发绾君心
    2021-02-07 04:35

    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.

    0 讨论(0)
提交回复
热议问题