JavaScript While loop: variable does not replace with - javascript

I have the following code:
j = 1;
while (j < 50) {
//requirement:
console.log(JSONitem [j]["criteria"]);
reqtest = Object.keys(JSONitem [j]["criteria"]);
....
j++;
}
But when I execute this, I get the following error:
TypeError: JSONitem[j] is undefined
The output object from the console.log part is right, but also in this line is the TypeErro above. I think, the "j" does not replace the number, but in the output console it works...
Thanks!

console.log(...JSONitem.map(el=>el.criteria));
Your code may behaves unexpected if the length of your array (?) changes. You should use the Array.prototype methods or the for..in, for..of or
for(i=0;i<array.length;i++)
loops to iterate over your Array.

Related

Uncaught TypeError: Cannot read property 'checked' of undefined Javascript

The first time the loop runs, there's no problem. The get's shown when the loop ends, and every other time the loop runs.
The .checked property works fine, to my knowledge, there's just the error...
Does someone know what to do about this?
My background in javascript isn't that broad, and I'm still learning.
Thanks you.
I have already tried .checked === true and
.checked == checked
...
In the code snippet below dishes is an array of radiobuttons.
for (i = 0; i <= dishes.length; i++) {
if (dishes[i].checked) {
switch (dishesClass) {
.........
}
}
}
I expect no error in the console, but there are multiple. Every time the loop ends, the console states the same error.
Uncaught TypeError: Cannot read property 'checked' of undefined
In your for loop you are testing if i is less than or equal to dishes.lengh. You just need to check if it is less than, since i starts from 0, as does array indexes in computing.
So just replace i <= dishes.length; with i < dishes.length;
Hope that helps
This code will work
for (i = 0; i < dishes.length; i++) {
if (dishes[i].checked) {
switch (dishesClass) {
.........
}
}
}
This resource, on Loops and Iteration may help you.
As pointed by #Alicia, the problem is in your loop condition i<= whereas it should be i<. The array index i tries to access an element outside of the array bounds on the last iteration. Array's index starts at zero and ends at the array length - 1

TypeError: DOM.addEventListener(...) is not a function error [duplicate]

This question already has answers here:
What are the rules for JavaScript's automatic semicolon insertion (ASI)?
(7 answers)
Closed 3 months ago.
I'm really confused how I can get console.log is not a function on line 1091. If I remove the closure below, line 1091 doesn't complain such error. Chrome Version 43.0.2357.130 (64-bit).
Here is the code:
$scope.columnNameChanged = function (tableColumn) {
setDirtyColumn(tableColumn);
//propagate changes to the key fields
for (var i = 0; i < $scope.tableIndexes.length; ++i) {
for (var j = 0; j < $scope.tableIndexes[i].columnName.length; ++j) {
if ($scope.tableIndexes[i].columnName[j] === tableColumn.previousName) {
console.log('xxx', $scope.tableIndexes[i].columnName[j])
(function (i, j) {
$timeout(function () {
console.log($scope.tableIndexes[i].columnName[j])
$scope.tableIndexes[i].columnName[j] = tableColumn.name.toUpperCase();
console.log($scope.tableIndexes[i].columnName[j])
});
})(i, j);
}
}
}
};
Solution
Simply put a semicolon (;) after console.log(…).
Explanation
The error is easily reproducible like this:
console.log()
(function(){})
It’s trying to pass function(){} as an argument to the return value of console.log() which itself is not a function but actually undefined (check typeof console.log();). This is because JavaScript interprets this as console.log()(function(){}). console.log however is a function.
If you didn’t have the console object you’d see
ReferenceError: console is not defined
If you had the console object but not the log method you’d see
TypeError: console.log is not a function
What you have, however, is
TypeError: console.log(...) is not a function
Note the (...) after the function name. With those it’s referring to the return value of the function.
The line break doesn’t separate these two expressions as separate statements because of JavaScript’s rules for automatic semicolon insertion (ASI).
Respect the ;
All these code snippets result in all sorts of unexpected errors if no semicolons are present:
console.log() // As covered before
() // TypeError: console.log(...) is not a function
console.log() // Accessing property 0 of property 1 of the return value…
[1][0] // TypeError: console.log(...) is undefined
console.log() // Like undefined-3
-3 // NaN
let a, b;
const array = Array.from({ length: 2 })
// Now, let’s use destructuring:
[a, b] = array; // ReferenceError: can't access lexical declaration 'array' before initialization
let a, b;
const array = Array.from({ length: 2 }).fill(1),
array2 = Array.from({ length: 2 })
// Now, let’s use destructuring. Attempt to get the two 1’s from `array` as `a` and `b`:
[a, b] = array;
console.log(a, b); // undefined undefined
Another Example
You see the (...) oftentimes with the use of chained methods or chained property accessors:
string.match(/someRegEx/)[0]
If that RegEx isn’t found, the method will return null and the property accessor on null will cause a TypeError: string.match(...) is null — the return value is null. In the case of console.log(...) the return value was undefined.
The error means that the return value of console.log() is not a function. You are missing a semicolon:
console.log('xxx', $scope.tableIndexes[i].columnName[j]);
// ^
which makes the following (...) of the IIFE to be interpreted as a function call.
Compare the error messages of
> var foo = {bar: undefined};
> foo.bar();
Uncaught TypeError: foo.bar is not a function
and
> var foo = {bar: function(){}};
> foo.bar()();
Uncaught TypeError: foo.bar(...) is not a function
2020 Update
One possible cause can be the declaration of var console somewhere in your script.
Use:
window.console.log(...);
instead. Worked for me.
I hope it helps
There is another way to encounter this error. console.log is not immutable and it is possible to accidentally overwrite the value.
console.log = 'hi';
In this case just reload the page to undo the damage.
I know this is not "THE" answer, but thought I would toss in the following
var console = $( data.message_target );
console.val( console.val() + data.message);
console.scrollTop(console[0].scrollHeight - console.height());
I had a textarea on the page I was calling "console". suddenly all my console.log() scripts gave the error "Uncaught TypeError: console.log is not a function at Object"
... and rightly so, because I used a reserved namespace for my object/var. I realized what I had done after reading his post, and for the sake of posterity: double check naming conventions.
cheers
"its always human error"
In react-native at least, the console seems to work without any import, so, removing import console = require('console'); or import console from 'console'; from the begin of my file fixed it for me. (the VS Code IDE seems to add that automatically sometimes )

Loop through object with multidimensional array

I use promises in angular to get some data from the server. In promises success I do
promise.success(function (data, status) {
for (i = 0; i <= data.data.length; i++){
$scope.anArray[i] = data.data[i][1] ;
}
}
I do this because data that came from the server have this structure
{"result":"answered","data":[["jake","508"],["amir","602"],["ben","450"]]}
and I ONLY want to get the numbers 508 , 602 and 450. But I always get the same error TypeError: Cannot read property '0' of undefined reffering to this line : $scope.anArray[i] = data.data[i][0] ;.
Those numbers are feeded to a library to create a chart. Sometimes the chart is created, some times is not. Even if it is created, the same error is always there.
I dont know how to fix that error and getting the chart to be always created without any problems. Looks like the code doesnt like the data.data[i][0] structure, having a simple array like data.data[i] doesnt create an error.
What should I do?
Thanks
Your for loop has an extra execution. You've initialized i to 0 but you've also used <= which means you are going to execute on array[array.length] which is out of bonds. That returns undefined and when you try to access the [0] index on that undefined you get that error.
Change to
for (i = 0; i < data.data.length; i++){
If you're able to do assignment personally I would go with
$scope.anArray = data.data.map(entry => entry[1]);
and skip the for loop entirely. Note if you want to avoid lambdas this would be
$scope.anArray = data.data.map(function(entry) { return entry[1]; });

Yet Another Uncaught TypeError: : Cannot read property 'replace' of undefined

I am writing a bit of JS code to switch classes for certain DOM elements.
Everything is working as it should, but I am also getting this error and this
prevents the code that follows to be executed.
I added a check to make sure that the array of elements is not empty as I thought
this was the problem. But still the error occurs. Debugging always showed a value for old_name when replace is called on it. Am I missing something JS-esque?
This is the part of the code that causes the error, specifically line 31:
if (w > MOBILE_THRESHOLD) {
responsive_elements = document.getElementsByClassName("desktop");
if (responsive_elements.length > 0) {
for (i in responsive_elements) {
var old_name = responsive_elements[i].className;
var new_name = old_name.replace("desktop", "mobile");
responsive_elements[i].className = new_name;
}
}
When necessary I will be happy to provide more code, or whatever information is needed. Thanks!
Never use for...in loops to iterate array-like objects!!!!!
In this case, the HTMLCollection has enumerable properties like item or namedItem. Accessing these won't return an HTML element, so className will be undefined.
To iterate properly, you can use one of these
for(var i=0; i<responsive_elements.length; ++i) {
// ...
}
[].forEach.call(responsive_elements, function(element, index, collection) {
// ...
});

why size of array printed as zero in javascript?

what is wrong with this below code ?
why it is printing size of array as zero?
function test() {
var arr = [];
for(var i = 0; i < 10; i++)
{
console.log('i ->' + i);
arr.push[i];
}
console.log('\n' + 'array length :' + arr.length);
}
--
Output:
i ->0
i ->1
i ->2
i ->3
i ->4
i ->5
i ->6
i ->7
i ->8
i ->9
array length :0
--
it is printing as zero(0)
push is a function.
You need to write arr.push(i) and not arr.push[i]. What you're doing in the latter is referring to arr.push as if it were an array, and then trying to access its ith subscript (or assuming that push is an object and trying to access a property that has the same value of i); it's effectively the same as writing a single line statement like so:
someArray[i];
Which doesn't really do anything.
Note: I have been bitten by this silly bug many times as well when I type too fast. ;)
Because .push[i] should be .push(i).
The reason you didn't get an error is that functions are objects in JavaScript, so you can legally get and set properties on functions.
What you were doing was fetching the the i property from the Array.prototype.push method (which will be undefiend).
console.log(arr.push[i]); // undefined
Probably worth noting that jsHint would catch this for you.

Categories