typescript 为什么我收到一条消息说 forEach 不是函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31162742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do I get a message saying forEach is not a function?
提问by Samantha J T Star
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)
类型错误: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.
有没有人知道可能有什么问题。我在其他地方使用了类似的代码,但每次都失败了。
采纳答案by Katana314
subjects
is an Object
, not an Array
, because of its {}
notation. You can loop through 1
and 100
as keys if you like using Object.keys(subjects)
. 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
是Object
,不是Array
,因为它的{}
符号。你可以通过循环1
和100
作为键,如果你喜欢使用Object.keys(subjects)
。你也可以启动它作为一个空数组([]
),然后设置的值subjects[1]
和subjects[100]
如果你喜欢,但没有速记直列方式只是定义数组的两个独立的指数没有插图中的。
回答by Josh
回答by phuzi
su.subjects
is an object, not an array and forEach
is not defined for Object
.
su.subjects
是一个对象,而不是一个数组,forEach
并且没有为 定义Object
。