最近在複习JS的时候,常对一些长得很像的东西感到困扰 @~@
像是等等要介绍的S三姐妹 split( )
、 slice( )
、splice( )
这三个真的有点像在玩文字游戏啊!!!!不过各自还是有点差别的,那就来一一破解吧
1. String.prototype.split( )
The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
1-1 解释:split()
把原字串依照指定的符号分割成子字串,并放入阵列中回传
1-2 特点:
会回传一个阵列,并以逗号隔开每个元素想要把字串转换为阵列时可使用1-3 语法:
本图撷取自MDN
1-4 示範:
/*split()*/let str = "Happy day Happy life."let arr = str.split(" ") //以"空格"分割字串console.log(arr); /*["Happy","day","Happy","life."]*/arr = str.split(" ",0) console.log(arr);/*[]*/
点我看DEMO
2. Array.prototype.slice()
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
2-1 解释:
slice在中文中有切片的意思,slice()
可以想像成从哪里开始去切,会回传一个新的阵列,为原阵列 start 至 end(不含 end)部分的浅拷贝(shallow copy),而原本的阵列并不会被修改
2-2 语法:
本图撷取自MDN
2-3 特点:
不会改变原阵列,而是会回传一个新的阵列切分的区域只包含起点start,不包含终点end2-4 示範:
/*slice()*/let arr2 = ["I","have","to","sleep","It\'s","1:25","a.m."]console.log(arr2.slice(5)); /*["1:25","a.m."]*/console.log(arr2.slice(1,-1)) /*["have","to","sleep","It's","1:25"]*/console.log(arr2.slice(1,7)) /*["have","to","sleep","It's","1:25","a.m."]*/
点我看DEMO
3. Array.prototype.splice()
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place(原地演算法).
3-1 解释:splice()
可以透过移除(removing)、替换(replacing)或是新增(adding)元素的方式来改变阵列的内容
3-2 语法:
本图撷取自MDN
3-3 特点:
会改变原阵列常使用在使用者与阵列中的资料互动3-4 示範:
/*splice()*/const season = ['spring', 'summer', 'winter'];season.splice(2, 0, 'autumn'); //从第二个开始 删除0个 增加autumnconsole.log(season); //["spring","summer","autumn","winter"]season.splice(3,1,'Hello Winter');console.log(season); /* ["spring","summer","autumn","Hello Winter"]*/
点我看DEMO
Summary 总结
split(separator,limit)
字串处理方法,回传一个阵列slice(start,end)
阵列处理方法,回传一个新的阵列splice(start,deleteCount,itim...)
阵列处理方法,回传一个阵列(我都想像成原阵列的Before/After)
以上是我自己的学习笔记,除了日后可以给自己看,也希望能帮助到有需要的人^ ^ 所学不精,若有解说不详尽、错误之处欢迎指教,阿哩嘎都
参考资料
MDN-split()
MDN-splice()
MDN-slice()
深拷贝与浅拷贝