在leetcode上刷題的時候踩的坑,題目是這樣的

image.png
簡單思考了一下,用最簡單的雙循環(huán)就可以解決問題,于是習慣性用forEach遍歷了兩次
var twoSum = function(nums, target) {
nums.forEach(function(item,index){
nums.forEach(function(value,index2){
if(value != item){
var sum = item+value;
if( sum === target ){
return [index,index2];
}
}
});
})
};
結果發(fā)現(xiàn)函數(shù)返回值是undefined
百度了一下,發(fā)現(xiàn)是因為forEach多次執(zhí)行回調函數(shù),回調函數(shù)中使用return沒法直接終止forEach,只能終止單次的回調。所以return語句在forEach內部是無法跳出循環(huán)的。
解決方案:
1.方案一:js針對數(shù)組操作的另外兩個方法some()與every()
some():當內部return true時跳出整個循環(huán)
every():當內部return false時跳出整個循環(huán)
2.方案二:for/while語句老實循環(huán)
總結原因還是對forEach方法理解不夠到位