从对象创建一个新数组

时间:2016-02-19 05:35:12

标签: javascript object for-in-loop

我创建了一个JavaScript对象来获取字符在字符串中重复的次数:

function getFrequency(string) {
  //  var newValsArray =[];
    var freq = {};
    for (var i=0; i<string.length;i++) {
        var character = string.charAt(i);
        if (freq[character]) {
           freq[character]++;
        } else {
           freq[character] = 1;
        }
    }

    return freq;
}

现在,我正在尝试构建一个由键和键组成的新字符串。他们的属性(字母)&amp;如果数字(属性)多于一个,则字母重复的次数,但我一直未定义,我不知道原因:

function newString(freq){
  var newValsArray = [];
  for (var prop in freq) {
    if (freq[prop]>1){
      newValsArray.push(prop + freq[prop]);
    }
    else if (freq[prop] < 2){
      newValsArray.push(prop);
    }
  }
  return newValsArray;
}

我觉得我的语法不合适......如果有人有任何建议,我真的很感激......

3 个答案:

答案 0 :(得分:0)

您未明确返回newString()内的任何内容,因此会返回undefined。听起来你想要这样的东西:

return newValsArray.join('');

newString()的末尾构造一个实际的字符串(而不是返回一个数组)。通过此更改,newString(getFrequency("Hello there")将返回'He3l2o thr'

答案 1 :(得分:0)

&#13;
&#13;
	function getFrequency(string) {
	  //  var newValsArray =[];
	  var freq = {};
	  for (var i = 0; i < string.length; i++) {
	    var character = string.charAt(i);
	    if (freq[character]) {
	      freq[character] ++;
	    } else {
	      freq[character] = 1;
	    }
	  }

	  return freq;
	}

	function newString(freq) {
	  var newValsArray = [];
	  for (var prop in freq) {
	    if (freq[prop] > 1) {
	      newValsArray.push(prop + freq[prop]);
	    } else if (freq[prop] < 2) {
	      newValsArray.push(prop);
	    }
	  }
	  return newValsArray.join("");
	}

	var mystring = "Here are some letters to see if we have any freq matches and so on.";
	var results = newString(getFrequency(mystring));
	var elem = document.getElementById("results");
	elem.innerHTML = results;
&#13;
<div id="results"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您没有从newString函数返回任何内容。添加return newString;作为newString函数的最后一行。添加该行确实会导致返回某些内容,但我无法判断它是否符合您的预期。

var text = "asdfjhwqe  fj asdj qwe hlsad f jasdfj asdf alhwe sajfdhsadfjhwejr";
var myFreq = getFrequency(text);
show(myFreq);
var myNewValsArray = newString(myFreq);
show(myNewValsArray);

function getFrequency(string) {
  //  var newValsArray =[];
    var freq = {};
    for (var i=0; i<string.length;i++) {
        var character = string.charAt(i);
        if (freq[character]) {
           freq[character]++;
        } else {
           freq[character] = 1;
        }
    }

    return freq;
}

function newString(freq){
  var newValsArray = [];
  for (var prop in freq) {
    if (freq[prop]>1){
      newValsArray.push(prop + freq[prop]);
    }
    else if (freq[prop] < 2){
      newValsArray.push(prop);
    }
  }
  return newValsArray; // ******** ADD THIS LINE
}

function show(msg) {
  document.write("<pre>" + JSON.stringify(msg, null, 2) + "</pre>");
}