我对数据类型感到困惑

时间:2018-08-01 20:45:34

标签: javascript

我正在处理Hack Reactor准备程序问题,下面列出了该问题。我的问题是customerData的数据类型是什么?它似乎是一个对象,但是每个属性都以名称“ Joe”开头,然后是键值对。我认为JavaScript对象具有键值对的属性。

问题:

编写一个名为“ greetCustomer”的函数。

给定名称,“ greetCustomer”将根据该顾客访问该餐厅的次数返回问候语。请参考customerData对象。

问候语应该有所不同,具体取决于其保留的姓名。

Case 1 - Unknown customer ( Name is not present in customerData ): 

var output = greetCustomer('Terrance');
console.log(output); // --> 'Welcome! Is this your first time?'

Case 2 - Customer who has visited only once ( 'visits' value is 1 ):

var output = greetCustomer('Joe');
console.log(output); // --> 'Welcome back, Joe! We're glad you liked us the first time!'

Case 3 - Repeat customer: ( 'visits' value is greater than 1 ):

var output = greetCustomer('Carol');
console.log(output); // --> 'Welcome back, Carol! So glad to see you again!'

Notes:
* Your function should not alter the customerData object to update the number of visits.
* Do not hardcode to the exact sample data. This is a BAD IDEA:


if (firstName === 'Joe') {
  // do something
}

Starter Code :
*/

var customerData = {
  'Joe': {
    visits: 1
  },
  'Carol': {
    visits: 2
  },
  'Howard': {
    visits: 3
  },
  'Carrie': {
    visits: 4
  }
};

function greetCustomer(firstName) {
  var greeting = '';
  // your code here

  return greeting;
}

3 个答案:

答案 0 :(得分:2)

它是一个对象。

对象文字的语法为{},其中包含一组键:用逗号分隔的值对。

键可以是字符串或标识符(在这种情况下,它们是字符串),并且值可以是解析为值的任何表达式(在这种情况下:更多对象文字)。

答案 1 :(得分:0)

您的数据是一个包含对象的对象。

第一个对象键是name,返回的对象键是visits。

var customerData = {
  'Joe': {
    visits: 1
  },
  'Carol': {
    visits: 2
  },
  'Howard': {
    visits: 3
  },
  'Carrie': {
    visits: 4
  }
};

function greetCustomer(firstName) {
  var greeting = '';
  var customer = customerData[firstName]
  if (!customer) {
    greeting = 'Hello New Customer';
  } else {
    var visits = customer.visits;
    switch (visits) {
      case 0:
        greeting = 'Hello New Customer';
        break;
      case 1:
        greeting = 'Thanks For Coming Back';
        break;
      case 2:
      default:
        greeting = 'Thanks For Being A Regular';
        break;
    }
  }

  return greeting;
}

console.log(greetCustomer('Felix'))
console.log(greetCustomer('Joe'))
console.log(greetCustomer('Howard'))

答案 2 :(得分:-2)

customerData看起来是JSON形式。

一些JSON结构类型如下:

{key: value}
{a: {a:b}}
{a : {[b,c,d]}}

有多种方法可以解析所需形式的JSON。 JSON序列化和反序列化也可能有所帮助。