连接值时出现Javascript错误

时间:2015-08-11 16:13:44

标签: javascript arrays string

我正在'codewars'网站上尝试Javascript质询,其中的说明是:

实现一个喜欢:: [String] - >的函数String,必须包含输入数组,包含喜欢项目的人的姓名。它必须返回显示文本,如示例所示:

likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"
For more than 4 names, the number in and 2 others simply increases.

我的尝试是这样的:

function likes(names) {
  var response = "a"
  console.log(names[0]);
  if (names.length === 0) {
    response = 'no one likes this';
  }
  else if (names.length === 1) {
    response = names[0] +' likes this';
  }
  else if (names.length === 2) {
    response = names[0] + ' and' + names[1] ' like this';
  }
  else if (names.length === 3) {
    response = names[0] + ',' + names[1] + ' and' + names[2] + ' like this';
  }
  else {
    response = names[0] + ',' + names[1] + ' and' + (names.length-2).toString() + ' others like this';
  }
  return response;
}

并返回此错误:

kata: Unexpected token:44 response = names[0] + ' and' + names[1] ' like this';

是不是可以将数组内的字符串值与另一个字符串连接起来?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:5)

您在此处缺少+签名

response = names[0] + ' and' + names[1] ' like this';

试试这个

response = names[0] + ' and' + names[1] +' like this';

答案 1 :(得分:1)

你在这一行忘了+

response = names[0] + ' and' + names[1] + ' like this';

不重要,但你也忘记了;和'和'应该是'和'

function likes(names) {

    var response = "a";

    if (names.length === 0) {
        response = 'no one likes this';
    } else if (names.length === 1) {
        response = names[0] + ' likes this';
    } else if (names.length === 2) {
        response = names[0] + ' and ' + names[1] + ' like this';
    } else if (names.length === 3) {
        response = names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this';
    } else {
        response = names[0] + ', ' + names[1] + ' and ' + (names.length - 2).toString() + ' others like this';
    }
    return response;
}