[英]Why do I get a message saying forEach is not a function?
In typescript I defined: 在我定义的打字稿中:
class SubjectService implements ISubjectService {
subject: any;
subjectId: number = 0;
subjects = {
"1": { "id": 1, "name": "Java" },
"100": { "id": 100, "name": "Test" }
};
static $inject = [
"$http",
"appConstant",
];
constructor(
public $http: ng.IHttpService,
public ac: IAppConstant
) {
}
}
I then in my constructor have this code: 然后我在我的构造函数中有这个代码:
class SubjectController {
static $inject = [
"$scope",
"subjectService"
];
constructor(
public $scope,
public su: ISubjectService
) {
$scope.su = su;
$scope.rowClicked = (subject, $index) => {
var self = this;
if (subject.current && subject.current == true) {
return;
}
su.subjects.forEach(function (subject) {
subject.current = false;
});
su.subject = subject;
su.subject.current = true;
}
}
}
But when this runs I am getting a message saying: 但是当这个运行时,我收到一条消息说:
TypeError: su.subjects.forEach is not a function at Scope.SubjectController.$scope.rowClicked ( http://localhost:1810/app/controllers/SubjectController.js:12:25 ) TypeError:su.subjects.forEach不是Scope.SubjectController中的函数。$ scope.rowClicked( http:// localhost:1810 / app / controllers / SubjectController.js:12:25 )
Does anyone have any idea what might be wrong. 有谁知道什么可能是错的。 I used similar code in other places but here it fails each time.
我在其他地方使用过类似的代码,但每次都失败了。
subjects
is an Object
, not an Array
, because of its {}
notation. subjects
是一个Object
,而不是一个Array
,因为它有{}
符号。 You can loop through 1
and 100
as keys if you like using Object.keys(subjects)
. 如果您喜欢使用
Object.keys(subjects)
可以将1
和100
作为键循环。 You could also start it out as an empty array ( []
) and then set the values of subjects[1]
and subjects[100]
if you like, but there's no shorthand inline way to just define two separated indices of an array without the inbetween ones. 您也可以将其作为空数组(
[]
)启动,然后根据需要设置subjects[1]
和subjects[100]
的值,但是没有简写内联方式来定义数组的两个分离索引而没有介于两者之间。
su.subjects
是一个对象,而不是一个数组,而且没有为Object
定义forEach
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.