var arrange = function (arr) {
var result = [],temp = [];
arr.sort(function (source, dest) {
return source - dest;
}).concat(Infinity).reduce(function (source, dest) {
temp.push(source);
if (dest - source > 1) {
debugger;
if (temp.length !== 1) {
temp.splice(1, temp.length - 2)
temp = temp.join('~')
console.log(temp)
}
temp = temp.toString()
result.push(temp);
console.log(temp)
temp = [];
}
return dest;
});
return result;
};
arrange([1, 3, 4, 5, 8, 9, 10000000000, 22254255522])
//1 3~5 8~9 10000000000 22254255522
用到的方法说明
sort() 方法用于对数组的元素进行排序。
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b}); //1,5,10,25,40,100
concat() 方法用于连接两个或多个字符串。
var str1="Hello ";
var str2="world!";
var str3=" Have a nice day!";
var n = str1.concat(str2,str3);
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
// 四舍五入后计算数组元素的总和:
<button onclick="myFunction()">点我</button>
<p>数组元素之和: <span id="demo"></span></p>
<script>
var numbers = [15.5, 2.3, 1.1, 4.7];
function getSum(total, num) {
return total + Math.round(num);
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
}
</script>
// 相加总和是24
push,splice,join: 用法见数组常用方法