将一个字符串数组解析为一个新的数组javascript

时间:2015-03-18 16:16:52

标签: javascript arrays

我想遍历一个字符串数组并将这些字符串拆分到某个字符上,然后将这些新字符串提供给一个数组,例如。从第一个数组中取出字符串“val:key”,然后使用函数从数组中检索字符串,并将其“>”拆分为一个包含[“val”,“key”]的新数组。这是我到目前为止,在底部是console.log时返回的内容。

var dict = [];
dict.push("me; pro: myself");
dict.push("labor, laboris; n: work");
dict.push("voco, vocare, vocavi, vocatum; v: call");

function parseDict(arr){
/* parseDict takes a dictionary entry and splits it between its latin  part and its part of speech/english translation*/
  var dictFinal = [];
  arr.toString();
  for (i = 0; i < arr.length; i++){
    dictFinal[i] += arr[i].split(";");
  }
  return dictFinal;
}

console.log(parseDict(dict)) prints out 
[ 0: "undefinedme; pro: myself"
  1: "undefinedlabor, laboris; n: work"
  2: "undefinedvoco, vocare, vocavi, vocatum; v: call"
]

为什么它不会在“;”上分成两个字符串,为什么它返回一个未定义的值?

3 个答案:

答案 0 :(得分:4)

未定义,因为您正在对空数组索引

执行+=
dictFinal[i] += arr[i].split(";");
             ^^

首次传递dictFinal[i]未定义,因此它是

dictFinal[i] = undefined + arr[i].split(";");

你可能只想要

dictFinal[i] = arr[i].split(";");

答案 1 :(得分:0)

使用dictFinal.push(...)dictFinal[i] = ...

调用arr.toString();对您的案件没有太大作用;它只是从数组中生成一个字符串,然后将其分配给变量/返回等...


var dict = [];
dict.push("me; pro: myself");
dict.push("labor, laboris; n: work");
dict.push("voco, vocare, vocavi, vocatum; v: call");

function parseDict(dict) {
  // considered that you know the final length of the final
  //   length of the array you could use: new Array(dict.length)
  var dictFinal = []; 
  for (i = 0; i < dict.length; i++) {
    dictFinal[i] = dict[i].split(";");
  }
  return dictFinal;
}

console.log(parseDict(dict)); // [["me"," pro: myself"],["labor, laboris"," n: work"],["voco, vocare, vocavi, vocatum"," v: call"]]

+=将尝试获取变量中的任何内容,并使用等号右侧的任何内容进行concat / add:

var a = 'abc';
a += 'def';
console.log(a); // abcdef

var b = 1;
b += 1;
console.log(b); // 2

// and your's case:
var c; // here c === undefined (your case dictFinal[i] === undefined)
c += 'ABC';
console.log(c); // undefinedABC

var my_array = [1,2,3];
// .toString() is called on the array so the concatenation can happen:
// It would be the same as writing:
//    'my_string' + my_array.toString();
// or 'my_string' + my_array.join(','); 
var d = 'my_string' + my_array;
console.log(d); // my_string1,2,3

答案 2 :(得分:0)

如果你真的需要+ =并且不想看到'UNDEFINED',可以试试:

dictFinal[i] = ((typeof dictFinal[i]!=='undefined') ? dictFinal[i]+arr[i].split(";") : arr[i].split(";"));