JavaScript 中 2个数组对比取 相同的元素,代码该...
发布网友
发布时间:2022-04-22 09:03
我来回答
共3个回答
热心网友
时间:2024-09-01 18:55
如果数组中个元素是字符串,这么做方便,如果不是,那就用@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());
热心网友
时间:2024-09-01 19:00
<button onclick="doclick()">按钮</button>
<script type="text/javascript">
function doclick(){
//调用一楼的代码
}
</script>
热心网友
时间:2024-09-01 19:01
var arry1 = ['a','b','c','d'];
var arry2 = ['x','b','c','y'];
var arry3 = new Array();
var j = 0;
for(var i=0;i<arry1.length;i++){
for(var k=0;k<arry2.length;k++){
if(arry1[i]==arry2[k]){
arry3[j]=arry1[i];
++j;
}
}
}
//array3中存放的就是['b','c']
return array3;