我製作了一個Typescript 遊樂場來向您展示代碼和輸出。我不明白為什麼當我使用.forEach
和for in
循環時,我的代碼中沒有相同的結果。
我做了 2 個函數來修剪所有的身體參數。第一個函數使用.forEach()
和第二個使用for in
。
下面是函數:
function trimWithForEach(obj: any): any {
if (obj !== null && typeof obj === 'object') {
Object.keys(obj).forEach(function (prop) {
// if the property is an object trim it
if (typeof obj[prop] === 'object') {
return trimWithForEach(obj[prop]);
}
// if it's a string remove begin and end whitespaces
if (typeof obj[prop] === 'string') {
obj[prop] = obj[prop].trim();
}
});
}
}
function trimWithForIn(obj: any): any {
if (obj !== null && typeof obj === 'object') {
for (var prop in obj) {
// if the property is an object trim it
if (typeof obj[prop] === 'object') {
return trimWithForIn(obj[prop]);
}
// if it's a string remove begin and end whitespaces
if (typeof obj[prop] === 'string') {
obj[prop] = obj[prop].trim();
}
}
}
}
有了forEach()
我想要的好結果,它會修剪我的全身。但是for in
我有一個問題,因為只有第一個object
條件被觸發來進行我的遞歸調用,如果我有其他對像類型,它們將被忽略。遞歸調用在for in
循環中的所有 body 對像中只工作一次,我不知道為什麼。
你能幫我理解嗎?
在for..in
循環中,return
它在第一次遇到條件為真時讓您退出功能。這就是為什麼後面的項目永遠不會被處理的原因。
我不太確定您在這裡嘗試做什麼,但是“forEach”和“for...in”在“return”方面的工作方式之間存在基本差異。
在for...in
return
返回值失去作用,但forEach
在return
不工作。
為了更清楚,請看下面的簡單示例
var testfn = function() {
let a = [1,2,3]
let b = a.forEach(el => {
if ( el == 2 )
return el
})
console.log("Came here!")
console.log({b})
}
var testfn1 = function() {
let a = [1,2,3]
for ( let i in a ){
if ( a[i] == 2 )
return a[i]
}
console.log("Came here!")
console.log({a})
}
testfn()
testfn1()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句