简体   繁体   中英

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. 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`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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