[英]Subtract and get a clean number from the total length of the array [Javascript]
I have this code here: 我在这里有此代码:
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'
}}
My main problem is in line 5. I need to subtract 2 from the length of the array and concat that to the string. 我的主要问题在第5行。我需要从数组的长度中减去2,并将其连接到字符串。 Unfortunately for me, I have no idea how this can be done, and mine is wrong, obviously.
对我来说不幸的是,我不知道如何做到这一点,显然我的想法是错误的。 Thanks in advance.
提前致谢。
You have to enclose the numeric subexpression in parentheses to prevent it from being part of the larger string concatenation process: 您必须将数字子表达式括在括号中,以防止它成为较大的字符串连接过程的一部分:
return names[0]+ ', ' + names[1] + ' and ' + (names.length - 2) + ' others like this';
With that, the numeric subtraction subexpression will be evaluated separately, and the result of it will be concatenated into the string. 这样,将分别计算数字减法子表达式,并将其结果串联到字符串中。
除了Pointy的答案 ,我认为模板字符串更干净:
return `${names[0]}, ${names[1]} and ${names.length - 2} others like this`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.