需要准备的材料分别是:电脑、html编辑器、浏览器。
1、首先,打开html编辑器,新建html文件,例如:index.html。
2、在index.html的<script>标签中,输入js代码:
var a = [1, 6, 8, 5, 23, 6, 6, 7, 8], b = [], c = []
for (var i = 0i <a.lengthi++) {
if (c.indexOf(a[i]) === -1) {
c.push(a[i])
} else {
b.push(a[i])
}
}
document.body.innerText = b
3、浏览器运行index.html页面,此时会打印出数组a中重复的数据。
function findSame(arr) {arr.sort()
for (var i = 0 i < arr.length - 1 i++) {
if (arr[i] == arr[i + 1]) {
alert("包含相同元素,相同值为:" + arr[i])
return true
}
}
return false
}
findSame(["aaa", "ddd", "fff", "eee", "aaa"])
如果数组中个元素是字符串,这么做方便,如果不是,那就用@lyw_2008_happy的方法就行
var arr1 = ['a','b','c','d']var arr2 = ['x','b','c','y']
var long = arr1.length<arr2.length?arr2:arr1
var short = arr1.length<arr2.length?arr1:arr2
var str = ","+long.toString()+","
var result=[]
for(var i in short){
if(str.indexOf(","+short[i]+",")>=0){
result.push(short[i])
}
}
alert(result.toString())