JavaScript数组调用sort后返回undefined及存储异常问题求助
问题排查与解答
错误原因说明
你封装的排序函数本身没有问题,Array.sort() 传入(a,b) => a-b的比较函数就可以实现数字的升序排序,该方法会原地修改原数组同时返回排序后的数组,这部分逻辑完全正确。
你遇到的两类异常分别是以下原因导致的:
- 最初的undefined报错:你只完成了
outputarray = []的初始化,indexarray没有被赋值,初始值为undefined,调用indexarray.includes()时会直接抛出类型错误,表现为执行结果异常/undefined。 - 数组只能存储单个值的问题:属于
reduce方法的误用。reduce的设计目的是将数组聚合为单个返回值,你的回调既没有返回累加值,当前场景也完全不需要聚合能力,直接用forEach遍历第二个数组即可,这就是你猜测的reduce导致输出异常的核心原因。
提问背景
我正在尝试完成第一次LeetCode挑战,目前遇到了问题:对数组应用sort函数后显示undefined,我想不明白问题出在哪里,我只是想对数组做排序。我知道还有其他排序数组的方法,但我搞不懂自己写的sort方法为什么不生效,非常希望能得到相关解释。
编辑:我已经解决了undefined的问题,但现在数组似乎只能存储单个值,请问我有没有什么明显的写法错误?
编辑2:我猜测数组只存单个值是因为我使用了reduce,这好像是reduce的特性,我会再尝试,感谢大家的帮助。
最初的错误代码
'use strict'; // define variables let indexarray, outputarray = []; const arr1 = [9, 4, 9, 8, 4]; const arr2 = [4, 9, 5]; function arrsort(array) { const outputz = array.sort(function (a, b) { return a - b }); return outputz; }; // sort arrays let arr1s = arrsort(arr1); let arr2s = arrsort(arr2); // foreach in arr1, go through arr2 and check if current arr1 array value matches. if yes and current arr2 index val isnt present in 'indexarray', then add current arr2 array val to array 'outputarray' and current index val to 'indexarray'. arr1s.forEach(function (x, i) { arr2s.reduce(function (pval, cval, ival) { if (cval === x && !indexarray.includes(ival)) { indexarray.push(ival); outputarray.push(cval); }; }); });
最终提交的解决方案
const intersect = function (nums1, nums2) { // define variables let indexarray1 = []; let indexarray2 = []; let outputarray = []; const arrsort = function (array) { return array.sort(function (a, b) { return a - b }); }; // sort arrays && let nums1s = arrsort(nums1); let nums2s = arrsort(nums2); /* foreach in nums1, go through nums2, check if nums1 val (x) matches nums2 val (pval). if yes and current nums2 index val isnt present in 'indexarray', then add current nums2 array val to array 'outputarray' and current index val to 'indexarray'. */ if (1 <= nums1s.length) { nums1s.forEach(function (x, i) { if (nums2s.length <= 1000 && 0 <= x && x <= 1000 && typeof x === "number") { nums2s.forEach(function (pval, iv) { if (pval === x && !indexarray2.includes(iv) && !indexarray1.includes(i)) { indexarray1.push(i); indexarray2.push(iv); outputarray.push(pval); } }); } else { console.log("ERROR: some constraint is stopping the code from continuing. please check around ForEach."); }; }); } else { console.log("ERROR: nums1s constraint is stopping the code from continuing as its length is less than 1."); }; console.log("outputarray: " + outputarray); return outputarray; };
内容的提问来源于stack exchange,提问作者noobhuzi
相关产品推荐
相关产品推荐

