我制作了一個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 物件中只作業一次,我不知道為什么。
你能幫我理解嗎?
uj5u.com熱心網友回復:
在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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/339631.html
標籤:javascript 打字稿 循环
