将对象推入数组失败

时间:2015-12-07 04:59:01

标签: javascript jquery

我试图将对象推入新阵列。

>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ\x8a\x8c\x8e\x9f\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde'
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz\x83\x9a\x9c\x9e\xaa\xb5\xba\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
>>> string.whitespace
'\t\n\x0b\x0c\r '

我得到的结果是我的对象获得了相同的结果,我做错了哪一部分?

3 个答案:

答案 0 :(得分:0)

在for循环中分配空temp_obj,如下面的代码:

var final = [],temp_obj;  

for (var i = 0; i < obj.length; i++) {
  temp_obj = {};
  var splitted = obj[i].split(":")[0]
  if (obj[i] != null && obj[i] != '') {
     temp_obj["name"] = splitted;
  }

  final.push(temp_obj);
}

console.log(final)

答案 1 :(得分:0)

尝试将null和空检查条件设置为一步到顶。如下所示,其他恶习你会得到零点问题。

Scanner console = new Scanner(System.in);

//where the menu would be
String menuInput;

    //if what user inputs isn't "1", "2" or "3", an error message is shown
    do {
        menuInput = console.next(); 
        if (!menuInput.equals("1") && !menuInput.equals("2") && !menuInput.equals("3")) {
            System.out.println("Enter Valid Input");
        } 
    } while (!menuInput.equals("1") && !menuInput.equals("2") && !menuInput.equals("3"));

答案 2 :(得分:0)

final.push()应位于循环内(demo

var obj = [ 'a:b', 'c:d', 'e:f' ], // just guessing
  final = [],
  temp_obj = {};

for (var i = 0; i < obj.length; i++) {

  var splitted = obj[i].split(":")[0];
  if (obj[i] !== null && obj[i] !== '') {
    temp_obj.name = splitted;
    final.push( temp_obj );
  }

}

console.log(final);