猿问

试图将数字保留在只有 5 位数字和只有数字 2,3,5,7 的数组中

我试图摆脱产品数组中没有质数或没有 5 位数字的所有数字。在最后一个 for 循环中拼接它们之后,products 数组仍然有不满足我的 if 条件的数字。


let arr1 = [222, 223, 225 ,227, 232, 233, 235, 237,252, 253, 255, 257, 272, 273, 275, 277, 322, 323, 325, 327, 332, 333, 335, 337, 352, 353, 355, 357, 372, 373, 375, 377, 522, 523, 525, 527, 532, 533, 535, 537, 552,553,555, 557, 572, 573, 575, 577, 722, 723, 725, 727, 732, 733, 735, 737, 752, 753, 755, 757, 772, 773, 775, 777]


let arr2 = [22, 23, 25, 27, 32, 33,35, 37, 52, 53, 55, 57, 72, 73, 75,77]


products = []  

for (var i=0; i< arr1.length; i++){

  for (var j=0; j< arr2.length; j++){

    products.push(arr1[i]*arr2[j])


  }

}

// console.log(products.length);



function not_prime(num){

  var str1 = num.toString()


  if ( 

    str1.indexOf(2) > -1 || 

    str1.indexOf(3) > -1 || 

    str1.indexOf(5) > -1 || 

    str1.indexOf(7) > -1 ||

    str1.length != 5) {

    return false;

    }

  return true;

}


for (var i=0; i< products.length; i++){

  if (not_prime(products[i])) {

    products.splice(i, 1);

  }

}


console.log(products)


catspeake
浏览 187回答 2
微课
2回答

小唯快跑啊

问题不是很清楚,但是看看这个:const arr1 = [222, 223, 225 ,227, 232, 233, 235, 237,252, 253, 255, 257, 272, 273, 275, 277, 322, 323, 325, 327, 332, 333, 335, 337, 352, 353, 355, 357, 372, 373, 375, 377, 522, 523, 525, 527, 532, 533, 535, 537, 552,553,555, 557, 572, 573, 575, 577, 722, 723, 725, 727, 732, 733, 735, 737, 752, 753, 755, 757, 772, 773, 775, 777];const arr2 = [22, 23, 25, 27, 32, 33,35, 37, 52, 53, 55, 57, 72, 73, 75,77];const products = [];arr1.forEach(q => {&nbsp; arr2.forEach(v => {&nbsp; &nbsp; let n = q*v, s = n.toString();&nbsp; &nbsp; if(s.length === 5 && s.match(/^[2357]+$/))products.push(n);&nbsp; });});console.log(products);

鸿蒙传说

使用Array.filter()和Array.some这里。请参阅内联评论。let arr1 = [222, 223, 225 ,227, 232, 233, 235, 237,252, 253, 255, 257, 272, 273, 275, 277, 322, 323, 325, 327, 332, 333, 335, 337, 352, 353, 355, 357, 372, 373, 375, 377, 522, 523, 525, 527, 532, 533, 535, 537, 552,553,555, 557, 572, 573, 575, 577, 722, 723, 725, 727, 732, 733, 735, 737, 752, 753, 755, 757, 772, 773, 775, 777]let arr2 = [22, 23, 25, 27, 32, 33,35, 37, 52, 53, 55, 57, 72, 73, 75,77];let primes = [2,3,5,7];products = []&nbsp;&nbsp;for (var i=0; i< arr1.length; i++){&nbsp; for (var j=0; j< arr2.length; j++){&nbsp; &nbsp; products.push(arr1[i]*arr2[j])&nbsp; }}// Return a filtered array of products that only contains// items from the original array that pass the provided callback// function's tests.let results = products.filter(function(item){&nbsp; &nbsp; // Test to see if item contains primes&nbsp; &nbsp; let prime = Array.from(item.toString()).some(function(char){&nbsp; &nbsp; &nbsp; return primes.indexOf(+char);&nbsp; &nbsp; });&nbsp; &nbsp; // Return item only if contains a prime and has 5 digits&nbsp; &nbsp; return prime && item.toString().length === 5 ? item : null;});console.log(results);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答