使用concat很方便也很简单:
let a = [1,2,3]
let b = [4,5,6]
let c = a.concat(b)
console.log(c)
浏览器输出如下
浏览器输出结果
js数组求和的方法
vararray = [1,2,3,4,5]
varsum =0
1.for循环
for(leti =0i <array.lengthi++) {
sum += array[i]
}
2.forEach
array.forEach(ele=>{
sum += ele
})
3.归并方法reduce()和 reduceRight()
//这两个方法都会迭代数组的所有项,然后构建一个最终返回的值。其中, reduce()方法从数组的第一项开始,逐个遍历到最后。
//而 reduceRight()则从数组的最后一项开始,向前遍历到第一项
varsum1 = array.reduce(function(prev, next, index, array){
returnprev + next
})
varsum2 = array.reduceRight(function(last, before, index, array){
returnlast + before
})
4.eval()
eval(array.join("+"))
<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"]组合的结果: