Javascript切片功能问题 [英] Javascript Slice Function Question
本文介绍了Javascript切片功能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个名为''count''的JS函数,它接受两个整数参数,并返回一个包含这两个参数之间所有数字的字符串。例如,如果我调用count(0,10),程序将显示''0,1,2,3,4,5,6,7,8,9,10,''。但是,我试图在10之后消除逗号,但到目前为止我没有运气。
function count(num1,num2)
{
var strCou = ' ';
for ( var input1 = num1; input1< = num2; input1 ++ )
{
strCou + = input1 + ,;
}
console .log(strCou);
}
count( 2 , 5 );
解决方案
查看原始代码,我们可以看到每个元素后面都附加了,。这很接近,但在纸上写下一堆数字的方式并不完全。
当我们手写一个列表时,我们插入, 之前每个元素除非它是第一个项目。
因此,一种方法涉及跟踪当前元素编号。然后我们在除第一个元素之外的每个元素之前添加,。
function count(num1,num2)
{
var strCou = ' ';
var i = 0 ;
for ( var input1 = num1; input1< = num2; input1 ++)
{
if (i!= 0 )
strCou + = ,;
strCou + = input1;
i ++;
}
console .log(strCou);
}
count( 2 , 5 );
尝试:
console .log(strCou。 substring( 0 ,strCou.length-1));
使用substring方法只需提供所需的字符串。上面,我们删除了最后一个字符。
function count(num1,num2 ){
var a = new Array < /跨度>();
for ( var i = num1; i< = num2; i ++)
a.push(ⅰ);
return a.join(' ,' 跨度>);
}
console .log(count( 0 , 10 跨度>));
I''ve created a JS function called ''count'' that accepts two integer parameters and returns a string containing all numbers between those two parameters. For example, if I called count(0,10) the program will display ''0,1,2,3,4,5,6,7,8,9,10,''. However, I am trying to eliminate the comma after the 10 but am having no luck so far.
function count(num1, num2)
{
var strCou = '';
for(var input1 = num1; input1 <= num2; input1++)
{
strCou += input1 + ", ";
}
console.log(strCou);
}
count(2,5);
解决方案
Looking your original code, we can see that ", " is appended after each element. That''s close, but not quite the way it works when writing a bunch of numbers on paper.
When we hand-write a list, we insert ", " before each element unless it''s the first item.
So, an approach involves keeping track of the current element number. We then add ", " before each element except the first one.
function count(num1, num2) { var strCou = ''; var i = 0; for(var input1 = num1; input1 <= num2; input1++) { if (i != 0) strCou += ", "; strCou += input1; i++; } console.log(strCou); } count(2,5);
Try:
console.log(strCou.substring(0,strCou.length-1));
Using substring method will just give the needed string. Above, we removed the last character whatever it was.
function count(num1,num2) { var a=new Array(); for(var i=num1;i<=num2;i++) a.push(i); return a.join(','); } console.log(count(0,10));
这篇关于Javascript切片功能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文