slice() 方法可从已有的数组中返回选定的元素。
arrayObject.slice(start,end)
slice方法测试网址:http://www.w3school.com.cn/tiy/t.asp?f=jseg_slice_array
slice用于数组:
<script type="text/javascript">
var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
document.write(arr + "<br />")
document.write(arr.slice(1) + "<br />")
document.write(arr)
</script>
输出:
George,John,Thomas
John,Thomas
George,John,Thomas
<script type="text/javascript">
var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"
document.write(arr + "<br />")
document.write(arr.slice(2,4) + "<br />")
document.write(arr)
</script>
输出:
George,John,Thomas,James,Adrew,Martin
Thomas,James
George,John,Thomas,James,Adrew,Martin
slice用于日期格式,也可以用于字符串,适用于中文
<script type="text/javascript">
var now = new Date();
document.write(now.getDate()+'-'+now.getMonth()+'<br>');
//格式化日,如果小于9,前面补0
var day = ("0" + now.getDate()).slice(-2);
//格式化月,如果小于9,前面补0
var month = ("0" + (now.getMonth() + 1)).slice(-2);
//拼装完整日期格式
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
document.write(today+"<br>");
var d="中国人";
var dt=("023423").slice(-2)
var dd=d.slice(-2);
document.write(dd + "-" +dt);
</script>
输出:
9-42018-05-09
国人-23
|