在 JavaScript 中检查数组的平方相似性
问题
我们需要编写一个 JavaScript 函数,该函数分别采用两个数字数组 arr1 和 arr2 作为第一个和第二个参数。
如果 arr2 中的每个元素都是 arr1 中任何元素的平方(不考虑出现顺序), 则我们的函数应返回 true。
例如,如果输入函数的是 -
输入
const arr1 = [4, 1, 8, 5, 9]; const arr2 = [81, 1, 25, 16, 64];
输出
const output = true;
示例
以下是代码 -
const arr1 = [4, 1, 8, 5, 9]; const arr2 = [81, 1, 25, 16, 64]; const isSquared = (arr1 = [], arr2 = []) => { for(let i = 0; i < arr2.length; i++){ const el = arr2[i]; const index = arr1.indexOf(el); if(el === -1){ return false; }; }; return true; }; console.log(isSquared(arr1, arr2));
Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.
输出
true
广告