forIn

说明

使用 iteratee 遍历对象的自身和继承的可枚举属性. iteratee 会传入3个参数: (value, key, object). 如果返回 false, iteratee 会提前退出遍历.

源码

用法

forIn.test.ts
1
import { forIn } from "../../utility/object/forIn";
2
3
describe('forIn tests...', () => {
4
5
test('method forIn should not exit', () => {
6
interface IReceivedProps {
7
name: string,
8
age: number,
9
skill: string,
10
};
11
12
const received: IReceivedProps = {
13
name: 'duanzhaoyang',
14
age: 21,
15
skill: 'program',
16
};
17
const expected = received;
18
19
forIn(received, (value, key) => {
20
expect(value).toBe(expected[key as keyof typeof expected]);
21
});
22
});
23
24
test('method forIn should exit when return `false`', () => {
25
interface IReceivedProps {
26
city: string[];
27
position: {
28
x: number,
29
y: number,
30
};
31
continue: boolean;
32
nextOne: number;
33
nextTwo: number;
34
};
35
36
const received: IReceivedProps = {
37
city: ['Dongguan', 'Foshan', 'Guangzhou'],
38
position: {
39
x: 100,
40
y: 200,
41
},
42
continue: false,
43
nextOne: 1,
44
nextTwo: 2,
45
};
46
47
const expected = received;
48
let count = 0;
49
50
forIn<IReceivedProps>(received, function (value, key, origin) {
51
count++;
52
expect(value).toBe(expected[key as keyof typeof expected]);
53
expect(this).toBe(origin);
54
55
if (key === 'continue') {
56
return false;
57
}
58
});
59
60
expect(count).toBe(3);
61
});
62
63
});
Copied!
最近更新 1yr ago
复制链接