// Array.prototype.sort() //原生自带的数组的排序方法;
var fruit = ['apples', 'bananas', 'Cherries'] //定义一个数组
fruit.sort()// ['Cherries', 'apples', 'bananas'] //按字母排序的结果
var scores = [1, 2, 10, 21] //定义一个数字排序,你发现其实还是按照字母序排列的
scores.sort()// [1, 10, 2, 21]
如果希望按照期望的数字排序。
scores.sort(function(a,b){return a-b})//这样的就可以了。结果为:21 10 2 1
var things = ['word', 'Word', '1 Word', '2 Words']
things.sort()// ['1 Word', '2 Words', 'Word', 'word']
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.
<html><head>
<title>js两个数组排列组合</title>
<script type="text/javascript">
var a = ["A","B","C"]
var b = ["1", "2","3"]
window.onload = function () {
var a1 = new objPL(a)//计算数组a的排列组合
var b1 = new objPL(b)//计算数组b的排列组合
var str = ""
var n = 0
//a1和b1的排列组合个数就是两者相乘(双层循环)
for (var i = 0 i < a1.length i++) {
for (var j = 0 j < b1.length j++) {
str += a1[i] + b1[j] + " "
n++
}
str += "<br/>"
}
document.write("共" + n + "个<br/>")
document.write(str)
}
//取数组的排列组合
function objPL(arr) {
this.a = arr
this.r = []
this.n = 0
//从M个数里面取N个(递归)
this.mGetN = function (curIndex, num, curSelect) {
if (num == 0) {
this.r[this.n++] = curSelect return
}
if (this.a.length - curIndex < num) return
this.mGetN(curIndex + 1, num - 1, curSelect + this.a[curIndex])
this.mGetN(curIndex + 1, num, curSelect)
}
for (var i = 1 i <= this.a.length i++) {
this.mGetN(0, i, "")
}
return this.r
}
</script>
</head>
<body></body>
</html>
["A","B","C"]与["1","2","3"]组合的结果:
这个只能用集合来实现。在JavaScript中,常用Array来存储和操作对象:
Array:
新建:var ary = new Array()或 var ary = []
增加:ary.push(value)
删除:delete ary[n]
遍历:for ( var i=0 i <ary.length ++i ) ary[i]