4
var name="nameSomnath";//remove name

I can do with slice()

var result = name.slice( 4 );

Same can be done with substring()

var result = name.substring( 4 );

So what makes them different. I have seen the link Here which elaborates the difference .But we can do the same thing by using any one method ie slice() or substring().So why there was need to have two methods.

4

5 回答 5

8

Even though it looks superficially like slice and substring do the same thing, the big difference is in how they handle negative arguments.

When JavaScript was first created in Netscape 2.0, there was just a substring method. If either of its arguments are negative, they are treated as 0.

When JavaScript 1.2 was introduced with Netscape 4.0, they wanted to add the behavior of allowing negative indexes to mean distances from the end of the string. They couldn't change substring to have this new behavior because it would break backward compatibility with scripts that expected negative indexes to be treated as 0, so they had to create a new function to support the added feature. This function was called slice, and was implemented on Array as well as String.

Another, smaller difference is that with substring the order of the arguments doesn't matter, so substring(1, 4) is the same as substring(4, 1). With slice, order does matter, so slice(4, 1) will just yield an empty string.

于 2013-08-14T06:32:44.033 回答
2

使它们不同的一项是您省略的第二个参数

  • slice:第二个参数是要取的范围的结束索引(不包括)。
  • substr: 第二个参数是从第一个参数指定的索引中获取的字符串的长度

您能否在string实例上完全复制一种方法的行为与另一种方法的行为?是的。为什么他们选择将两者都包括在内可能已经被历史遗忘了。我的猜测是熟悉。我敢打赌,市面上很少有框架有sliceforstrings但有很多substr.

于 2013-08-14T06:05:03.003 回答
1

编辑:哎呀-我错了-字符串也有切片方法!我将再次删除我的帖子-抱歉没有正确研究!!!或者,好吧,可能不会删除它,但至少在其中留下这个更正。;-)

您正在查看不同类的两种方法。substr只能应用于String-objects 而slice属于Array-objects。它们可能看起来与 yo 相似,但在内部它们以不同的方式工作,因为它们处理的数据不同。

顺便说一句,这不是一个 jQuery 而是一个普通的 JavaScript 问题。;-)

于 2013-08-14T06:03:15.507 回答
0

.slice(开始,结束)

不包括,给定的结束索引元素


子串

.substr(开始,长度

从开始位置到编号的提取。的字符。指定的


子串

.substring(开始,结束)

提取两个指定索引之间的字符


于 2013-08-14T06:11:54.070 回答
0

slice参数中是第一个索引和最后一个索引。在substr中,参数是第一个索引和长度。

于 2013-08-14T06:03:36.013 回答