Object exists but is still undefined in youtube response? - javascript

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.)

Related

get string from an array?

trying to loop on string array but it throws error foreach is not a function what is correct way to implement using typescript ?
main.ts
content = ["renewel","payments"]
if i do for loop
for (let i = 0, len = content.length; i < len; i++) {
console.log(content[i]);
}
it prints all indexs [r e n e etc
if do foreach
content.forEach(function(content){
console.log(content);
})
it throws error content.forEach is not a function
Your code works just fine; it's very likely you've mutated content's type in some way at some point in your code. Ensure any functions you may be passing it (content) to aren't mutating the original array.
You might also consider using newer syntax, like:
content.forEach(item => {
console.log(item);
});
or even
content.forEach(item=> console.log(item));
Two small things, by the way; there's no need to cache length in a for loop (JS engine does that for you), and I don't know if it matters or not... but you've misspelled 'renewal' ;)

javascript: cannot read property 'push' of undefined

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.

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.

Generating new variables to save loop results

I´ll try to be very specific about this topic.
So I have a "for" loop in javascript working just fine. The loop aims to retrieve the URLs of all the files existing in a target folder. The question is, how can I save the retrieved URLs into individual variables?
So, in order to make things easy, I won´t paste the code I´m using, I´ll just create a simple array and run a "for" loop as an example, so you guys can tell me how you would try to save the results into new variables.
So here's the example:
var index;
var arrayElements = ["FirstURL", "SecondURL", "ThirdURL"]
for (index = 0; index < arrayElements.length; index++) {
document.write (arrayElements[index]+"<br/>");
}
So, with that code, I can "print" the different URLs included in the array (I could use console.log of course, but I´m writing in notepad++, so I have to test the code with document.write)
So the question, how can I save each URL into an individual variable?
EDIT:
Ok, so reading the first answers, I think I must clarify some things.
The question is that I need to store the URLs in variables so I can call them later. So it´s not a question about "printing" the URLs.
The function eval()
I know eval is bad
var data = ["a", "b", "c"];
function makeIndvidualVariable(array){
var size;
try{
size = array.length;
for(var i = 0 ; i < size ; ++i){
if( eval(array[i]) != undefined){
eval("var "+array[i]+"="+array[i]+";");
}else{
throw "already exist variable : "+array[i];
}
}
}catch(e){
console.log(e);
}finally{
array = size = i = null;
}
}
makeIndvidualVariable(data);
You can obtain individual variables with window object (if i got you properly).
Use the thing with JS that enables you to declare variables in window scope.
var index;
var arrayElements = ["FirstURL", "SecondURL", "ThirdURL"]
for (index = 0; index < arrayElements.length; index++) {
window['variable'+index] = arrayElements[index];
}
// now variables are available globally (through window object)
document.write(variable0); // prints FirstURL
document.write(variable2); // prints ThirdURL
// etc.
Hope this helps.
Just for the sake of printing the urls stored in array one by one and avoid loops you can use this:
document.write (arrayElements.join("<br/>"));

Parse.com Relational Query

I am quite new to Parse and I am struggling with a particular query. I have a class User
a class Post
and a class Comment (I guess my configuration is pretty standard) I do not have enough reputation to post pictures - how sad that sounds - :-)
I have a query where basically I select all the posts (and the related users and ideally I would like to have all the comments related to the post) To do so I do:
var query = new Parse.Query("Post");
query.include("user");
query.find({
success: function(objects) {
for (var i = 0; i < objects.length; i++)
{
var object = objects[i];
console.log(object.id + object.get("user").get("imageUrl") + object.get('text'));
var commentquery = new Parse.Query("Comment");
commentquery.equalTo("post", object);
commentquery.find({
success: function(comments) {
console.log(object.id + object.get("user").get("imageUrl") + object.get('text'));
where basically I try to get the posts and then fetch the comments for each of them. Unfortunately, the second console log in my code always prints the same object (like ignoring the for loop).
I really don't know what am I doing wrong (maybe the callbacks or maybe the query setup) but I am not able to overcome this. Also, if any expert knows a better way of doing this without getting redundant with data or knows a good tutorial / book on Parse (apart from the Parse Documentation) I will be really grateful.
Thanks in advance!
Use an anonymous function to close your work on object.
for (var i = 0; i < objects.length; i++)
{
var object = objects[i];
(function(object){
//do stuff with object;
})(object);
}
You're using the most recent object because the work after the assignment has not yet finished so objects[i] is going to the next one too early. The extra function should help.
Or you can just
for (var i = 0; i < objects.length; i++)
{
(function(object){
//do stuff with object;
})(objects[i]);
}
Closures and the infamous loop problem

Categories

Resources