js从一个数组中取n个数,从第n个数开始,与之相邻的前和后各取一半;若前面不够一半时,从后面补上,若后面不够一半时,从前面补上。
<html>
<body>
<script type="text/javascript">
var index = 15
var howmany = 10
var start = 0
var end = start + howmany
var arr = '1234567890abcde67890'
var length = arr.length
var half = howmany / 2
var diffBefore = index - half // 当前项往前推N个数
var diffAfter = length - (index + half) // 当前项往后推N个数
if(diffBefore < 0) {
// 当前项小于要取的数量的一半
start = 0
} else {
start = diffBefore
end = index + half
}
if(diffAfter < 0) {
start = diffBefore + diffAfter
}
document.write(arr + "<br />")
document.write(arr.slice(start, end) + "<br />")
</script>
</body>
</html>
输出结果
1234567890abcde67890
abcde67890
网友评论