例一:数组中字符串按首字母判断
<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.sort())
</script>
输出:
George,John,Thomas,James,Adrew,Martin
Adrew,George,James,John,Martin,Thomas
完全可以把字母也改为数字,默认排序顺序是根据字符串Unicode
码点。
例二:数组中数字按照自身大小排序
<script type="text/javascript">
function sortNumber(a,b)
{
return a - b
}
var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"
document.write(arr + "<br />")
document.write(arr.sort(sortNumber))
</script>
输出:
10,5,40,25,1000,1
1,5,10,25,40,1000
sort()中可以加函数用于改变判断顺序的规则;
上面是正序,倒序为:
把
function sortNumber(a,b)
{
return a - b
}
改为
function sortNumber(a,b)
{
return b - a
}
当然不用上述方法,也可以在结尾给加上
arr.reverse()
将其倒序
耐用之处来了
sort()可以根据数组对象中的某个属性值进行排序,
var arr = [
{name:'zopp',age:0},
{name:'gpp',age:18},
{name:'yjj',age:8}
];
function compare(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
}
console.log(arr.sort(compare('age')))
输出:
如果要给html页面元素排序,可以根据元素私有id来给元素排序。
html部分:
<span class="show_choose">
<span data-val1="0">三星
<span class="back">×</span>
</span>
<span data-val1="2" >3.0英寸及以下
<span class="back">×</span>
</span>
<span data-val1="1">64G
<span class="back">×</span>
</span>
<span data-val1="3">双卡双4G
<span class="back">×</span>
</span>
</span>
js部分:
var main = $('.show_choose');
var arr = [];
$.each(main, function (index, item) {
arr.push(item)
})
$('.show_choose').empty()
arr.sort(function (a, b) {
return a.getAttribute('data-val1') - b.getAttribute('data-val1')
});
$.each(arr, function (index, item) {
$('.show_choose').find('.show_choose').append(item)
})
html页面将会改变:
<span class="show_choose">
<span data-val1="0">三星
<span class="back">×</span>
</span>
<span data-val1="1">64G
<span class="back">×</span>
</span>
<span data-val1="2" >3.0英寸及以下
<span class="back">×</span>
</span>
<span data-val1="3">双卡双4G
<span class="back">×</span>
</span>
</span>
大概就是这样了
<span data-val1="1">64G
<span class="back">×</span>
</span>