JavaScript的,怎么能这个功能可能返回一个空数组? [英] javascript, how can this function possibly return an empty array?

查看:109
本文介绍了JavaScript的,怎么能这个功能可能返回一个空数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function whatTheHeck(obj){
  var arr = []

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

  return arr
}

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

concat函数完全不能做任何事情。但是,如果我把萤火虫该行断点和运行线作为手表它工作正常。而对于循环迭代两次,但最终还是编曲等于[]。

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 [].

推荐答案

Array.concat 创建一个新的数组 - 它不会修改原来那么当前的code是实际上什么都没做。它不会修改改编

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});

如果你想只是添加单个项目到数组的末尾, .push()是一个更好的方法:

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});

这是我觉得有点混乱关于JavaScript数组方法的事情之一。一些修改原始数组,有的没有,也没有命名约定知道哪些做,哪些没有。你只需要阅读和了解哪些工作过来的。

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的,怎么能这个功能可能返回一个空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆