简体   繁体   English

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

[英]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.

相关问题 如何在Javascript中获取数组中变量的总数? - How to get total number of variables in an array in Javascript? 从每个对象数组中乘以 2 个值,然后将相加的数字相加以获得 Reactjs/Javascript 中的总数 - multiply 2 value from each array of objects then add the multiplied numbers to get a total number in Reactjs/Javascript 在 wordpress 文本字段中使用 javascript 从业务起始年份减去今年 - Subtract this year from starting year in business to get total years using javascript in a wordpress text field 获取对象数组中每个用户的点赞总数 - JavaScript - Get total number of likes for each user in an array of objects - JavaScript 如何从数组中减去数字以使总数为 0。我想跳过会使总数为负数的数字 - How can I subtract numbers from an Array to get my total to 0. I want to skip numbers that would make my total a negative JavaScript 如何从地图数组中获取长度 - JavaScript how to get a length from a map array 如何从输入框中减去总数的数字? - How to subtract number from the input box for Grand Total? 获取JSON中的对象总数,但Javascript Object.keys()。length返回未定义 - Get total number of objects in JSON but Javascript Object.keys().length returns undefined JavaScript:对字符串中的数字进行加减 - JavaScript: add or subtract from number in string 创建一个正则表达式以从列表中创建一个干净的数组,根据每个数字的长度对其进行过滤并检查其有效性(长度是否小于 4) - Create a regex for create a clean array from a list, filter it based on a length of each number and check its validity(whether length is less that 4)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM