javascript: cannot read property 'push' of undefined - javascript

I'm trying to fill up an Array with a number of elements given by the user. I'm doing this with a prompt window.
However, the code doesn't execute, and I get an error on line 9, telling me this:
Uncaught TypeError: Cannot read property 'push' of undefined at fillArrayWithNumberOfElements (line 9).
I searched for an answer online, but they are all pointing out that the array is not properly declared, while I'm pretty sure mine is.
Any help is appreciated, thanks in advance!
var emptyArray = [];
function askInput() {
return (prompt("Please enter a number: "));
}
function fillArrayWithANumberOfElements(array, numberOfElements){
for(var i = 0; i < numberOfElements; i++){
array[i].push(askInput());
}
return array;
}
fillArrayWithANumberOfElements(emptyArray, 5);

In fillArrayWithANumberOfElements, array is the array, not array[i]. So to push, just use
array.push(askInput());
not
// Not this
array[i].push(askInput());
Alternately if you like, use assignment:
array[i] = askInput();

push is a function attached to the prototype of the array type. You're accessing a specific element within the array.

Related

object with array type string causing a typeError

The best way to explain this is just to show you.
var condition = 70;
var formnames = new Array("wheelcheckbox1", "wheelcheckbox2","spokecheckbox","spokecheckbox2","tirecheckbox","tirecheckbox2","tirecheckbox3");
formnames.forEach(function(entry) {
console.log(obj.entry);
if(obj.entry == "") {
condition = condition - 10;
}
});
as you can see I used the console log to show how it needs to work
as that works perfect, however, using the array causes an error as
they're strings and not what the obj wants, it wants text without it being a string.
Any ideas?
for..in should not be used to iterate over an array. Consider using forEach instead.

Object exists but is still undefined in youtube response?

I'm having a little trouble with some Youtube API JS. I have troubleshooted for a while and I have annotated my code with comments so that you understand what the problem is. I know that their are several different things thay might be wrong. Anyway thanks for helping out!
request.execute(function(response) {
console.log(response.result.items); // Here you get an array of objects.
var results = response.result;
console.log(results.items.length);
var id = results.items.id;
for (id in results.items) {
console.log(results.items.id); // And here it is undedfine. When adding video.Id the console says cannot read property videoId of undefined.
console.log('if you read this the loop works');
}
});
You are trying to access an id property on an array, which doesn't exist (hence, undefined). The main problem is that for in in JavaScript is for iterating through object keys, not arrays. Use a regular for loop:
request.execute(function (response) {
var results = response.result;
for (var i = 0; i < results.length; i++) {
console.log(results[i]);
}
});
If you don't need to support IE8, you can use a .forEach().
(As a side note, read up a bit on for in with JavaScript, as your usage is a bit incorrect.)

TypeError: undefined is not an object string.split .split

So I was messing around with a simple javascript anagram function to compare 2 strings, however whenever I tried to use the .split operation in my sort function my code would error:
var wd;
function sortword(word){
wd = word;
var w = wd.split("");
w.sort();
return w;
}
caused
"TypeError: undefined is not an object (evaluating 'wd.split')"
http://jsbin.com/lebiwolive/1/edit?js,console
Why does this cause such an error? I've tried defining wd in various places but it does;t seem to make any difference. The code does even work correctly but I have this error in my console.
Check your for loop:
for (i=0; first_words.length; i++)
You didn't put any ending condition, so the loop keeps running after you've read the whole array.
Write this instead:
for (i=0; i<first_words.length; i++)

TypeError: Cannot read property "0" from undefined

I'm getting a very weird undefined error:
function login(name,pass) {
var blob = Utilities.newBlob(pass);
var passwordencode = Utilities.base64Encode(blob.getBytes());
var ss = SpreadsheetApp.openById("");
var sheet = ss.getActiveSheet();
var data = sheet.getDataRange().getValues();
var i=1;
while (name != data[i][0]){
Logger.log(data[i][0]);
i++;
}
if (passwordencode == data[i][1]){
UserProperties.setProperties({
"name" :name,
"pass" : passwordencode
});
Logger.log("You are logged in");
}
else if (passwordencode != data[i][1]) {
Logger.log("You are not logged in");
UserProperties.setProperties({
"name" : "",
"pass" : ""
});
}
}
Using Google Apps Script. The one that's undefined is the while statement where while(name != data[i][0]) claiming that you cannot read property "0" from undefined. What's weird about this, If I remove the data[i][0] in the while statement, it still works in the logger.log. And everywhere else. What the heck is going on?
EDIT: If I change the while to a if statement it also works.
The while increments the i. So you get:
data[1][0]
data[2][0]
data[3][0]
...
It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.
Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.
Ammend your while statement to this...
for(var iIndex = 1; iIndex <= data.length; iIndex++){
if (data[iIndex][0] === name){
i = iIndex;
break;
};
Logger.log(data[iIndex][0]);
};
Check your array index to see if it's accessed out of bound.
Once I accessed categories[0]. Later I changed the array name from categories to category but forgot to change the access point--from categories[0] to category[0], thus I also get this error.
JavaScript does a poor debug message. In your case, I reckon probably the access gets out of bound.
For me, the problem was I was using a package that isn't included in package.json nor installed.
import { ToastrService } from 'ngx-toastr';
So when the compiler tried to compile this, it threw an error.
(I installed it locally, and when running a build on an external server the error was thrown)
Under normal circumstances,out of bound of array when you encounter the error.
So,check uo your array subscript.

Cannot set property 'marginLeft' of undefined

Firstly, >>>FIDDLE HERE<<<
I put a series of divs in my webpage and used JavaScript to change their margins.
var inn = document.getElementsByClassName("line");
for (var i in inn) {
inn[i].style.marginLeft=40+"px";
}
Although it changed my margins already, an error reported in my console:
Uncaught TypeError: Cannot set property 'marginLeft' of undefined
So rest of my codes couldn't be executed.
Could you please help me to solve this problem? Thanks!
Take a look at the properties that your loop iterates over:
0
1
2
3
4
length
A for...in loop iterates over all the enumerable properties of an object. You shouldn't use it for array-like objects unless you really intend to do that.
0 through 4 work, but length doesn't have a style attribute, which is what your error says.
Use a regular for loop instead:
for (var i = 0; i < inn.length; i++) {
inn[i].style.marginLeft = 40 + "px";
}
Don't use for ... in ... it's slower and more error prone try this:
var inn = document.getElementsByClassName("line");
var i=0;
for (i=0;i<inn.length;i++) {
inn[i].style.marginLeft=40+"px";
}
next one shows the for ... in ... I think it may include some things that aren't Elements so the .style is undefined.
for(i in inn){
console.log(i);
}
Another possible solution which worked for me is instead of class name, try using by id. only when you explicitly don't need a class
change this line to
var inn = document.getElementsByClassName("line");
to
var inn = document.getElementById("line");
and definately make change in html file also.

Categories

Resources