繁体   English   中英

从数组的总长度中减去并得到一个干净的数字[Javascript]

[英]Subtract and get a clean number from the total length of the array [Javascript]

我在这里有此代码:

function likes(names) {
  if (names.length == 0) {
    return 'no one likes this';
}  else if (names.length >= 4) {
    return names[0]+ ', ' + names[1] + ' and' + names.length - 2 + 'others like this';
}  else if (names.length <4 && names.length >0){
return names[0] + ', ' + names[1] +' and ' + names[2] +' like this'
}}

我的主要问题在第5行。我需要从数组的长度中减去2,并将其连接到字符串。 对我来说不幸的是,我不知道如何做到这一点,显然我的想法是错误的。 提前致谢。

您必须将数字子表达式括在括号中,以防止它成为较大的字符串连接过程的一部分:

return names[0]+ ', ' + names[1] + ' and ' + (names.length - 2) + ' others like this';

这样,将分别计算数字减法子表达式,并将其结果串联到字符串中。

除了Pointy的答案 ,我认为模板字符串更干净:

return `${names[0]}, ${names[1]} and ${names.length - 2} others like this`;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM