如何在此条件中访问此对象键?

时间:2016-11-12 18:01:56

标签: javascript javascript-objects

编写一个函数countWords,当给定一个字符串作为参数时,返回一个对象,其中键是字符串中的单词,值是字符串中该单词的出现次数:

function countWords(string){
    string = string.split(" ");
    var newObj = {};
    for(var i = 0 ; i === newObj.string ; i++){
        if(newObj['i'] === newObj[string]){
           newObj[string[i]] = i ;
        }
    }
        return newObj;
    }
countWords("hello hello"); // => {"hello": 2}
countWords("Hello hello"); // => {"Hello": 1, "hello": 1}
countWords("The quick brown"); // => {"The": 1, "quick": 1, "brown": 1}

我意识到,因为您不需要计算拆分字符串的索引,所以您必须将条件从i < string.length更改为i === key value of of the objects。为什么我无法使用newObj.string访问字符串?

4 个答案:

答案 0 :(得分:1)

您可以使用reduce()代替for循环执行此操作。

function countWords(string) {
  return string.split(' ').reduce(function(r, e) {
    r[e] = (r[e] || 0) + 1;
    return r;
  }, {})
}
console.log(countWords("hello hello"))
console.log(countWords("Hello hello"))
console.log(countWords("The quick brown"))

使用for循环,您的代码就可以这样。

function countWords(string) {
  var string = string.split(" ");
  var newObj = {};

  for (var i = 0; i < string.length; i++) {
    newObj[string[i]] = (newObj[string[i]] || 0) + 1
  }
  return newObj;
}
console.log(countWords("hello hello"));
console.log(countWords("Hello hello"));
console.log(countWords("The quick brown"));

答案 1 :(得分:0)

&#13;
&#13;
function countWords(string){
  return string
    .split(" ")
    .reduce((acc, curr) => {
      if (curr in acc) {
        acc[curr]++
      } else {
        acc[curr] = 1
      }
      return acc
    }, {})
}
console.log(countWords("hello hello"));
console.log(countWords("Hello hello"));
console.log(countWords("The quick brown"));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以通过以下方式使用hasOwnProperty函数来检查JavaScript对象中是否存在属性,如果它确实增加了计数,如果它没有,则将计数初始化为1。

function countWords(data) {
  var words = data.split(" ");
  var item = {};
  for (var i = 0; i < words.length; i++) {
    var prop = words[i];
    item.hasOwnProperty(prop) ? item[prop] ++ : item[prop] = 1;
  }

  console.log(item);
  return item;
}

countWords("hello hello"); // => {"hello": 2}
countWords("Hello hello"); // => {"Hello": 1, "hello": 1}
countWords("The quick brown"); // => {"The": 1, "quick": 1, "brown": 1}

答案 3 :(得分:0)

newObj[string[i]] = (newObj[string[i]] || 0) + 1 根据我的理解,此语句用于检查重复性 假设您创建了一个空对象,然后使用此语句“(newObj[string[i]] || 0) + 1”将键值对存储在其中,您正在检查键的默认值是否为零,如果为零然后,如果同一个键有多个值,则将其值加 1,这样您就可以获得数组中的唯一值

示例

const uniqueValues = arr => {
  let newObj = {}
  for (let val of arr){
    newObj[val] = [newObj || 0] + 1;
  }
  return (Object.keys(newObj).length);
}
uniqueValues([1,1,1,1,1,2]);
相关问题