Typescript .forEach and for in behavior



我创建了一个Typescript playground来展示代码和输出。我不明白为什么当我使用.forEachfor 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"one_answers"for…"的方式有一个基本的区别。In ' works with 'return'.

for...inreturn返回值的功能,但在forEachreturn不工作。

看下面这个简单的例子,看得更清楚

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()