Why do I get a message saying forEach is not a function?
Solution 1
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.
Solution 2
I would also note that forEach
is not implemented in all versions of browsers (looking at you, IE 8) since forEach
was not included until ECMA 5.1. See forEach
Solution 3
su.subjects
is an object, not an array and forEach
is not defined for Object
.
Samantha J T Star
I'm in the Philippines so if you send some comment I may not be able to answer if I am sleeping :-) The good thing is I work all day until late each night.
Updated on August 21, 2022Comments
-
Samantha J T Star over 1 year
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)
Does anyone have any idea what might be wrong. I used similar code in other places but here it fails each time.