Javascript Uncaught Syntax Error: Unexpected token . for array.length - javascript

I am extremely new to programming and an assignment from class was to create a voting website. I was able to create variables and put them into local storage, as such:
var eventName = document.getElementById("eventName").value;
document.getElementById("p1").innerHTML = (eventName);
localStorage.setItem("eventName", eventName)
localStorage.getItem("eventName")
Now, we were supposed to include all of this into an array so that we can get multiple eventNames. My teacher is never really clear with his instructions, so this is what I got now:
var eventName = [];
var index ;
function submitNewEvent() {
eventName[index] = document.getElementById("eventName").value;
index = index + 1;
var eventNmString = JSON.stringify (eventName);
localStorage.setItem("eventName", JSON.stringify (eventName));
localStorage.getItem("eventName")
array = JSON.parse(localStorage.getItem("eventName"));
array = parse;
var output = "";
for (var i=0, array.length > i; i++){
output += "<p>"+array[i];
}
document.getElementById("p1").innerHTML = (output);
I would really appreciate any help if anyone can explain to me what I did wrong.

Here's the syntax error (the error message should point to that line as well):
for (var i=0, array.length > i; i++){
// ^
The array.length expression is not a valid identifier name, like i is (in a statement like var i=0, array=5; or so). You wanted to use a semicolon there:
for (var i=0; i < array.length; i++){
// ^

Related

Getting through all entries in JS by queryselector

I'm trying to get some informations from the page.
If there is one entry I can do that by
var z = document.querySelector('div.class').innerText;
and then get it by +z somewhere where I need the value.
But if there are more entries it will get only first.
I'm trying to do sth like that to get them all:
var x = document.querySelectorAll('div.class');
var i;
for (i = 0; i < x.length; i++) {
x[i].innerText;
}
But definitely something's wrong with this code. I'm not really familiar with JS, could you help me how to get all entries?
You can achieve that by using getElementsByClassName('class').
The script would be sort of:
let list = document.getElementsByClassName('class');
for (let i = 0; i < list.length; i++) {
console.log(list[i].innerText);
}
https://jsfiddle.net/esjcaqwb/
Your code looks ok, heres a working example that might be useful.
var x = document.querySelectorAll('.example');
var r = document.querySelectorAll('.result')
var i;
for (i = 0; i < x.length; i++) {
r.innerText += x[i].innerText;
}
What was going wrong with your code? In the example you provided, you're getting the value but not doing anything with it.
With your actual code you are not doing anything in the loop, the statement x[i].innerText; does nothing.
If you want to get these elements contents in an array you can use:
var results = Array.from(x).forEach(function(el){
return el.innerText;
});

Can I concat a string and a variable to select a DOM element in JavaScript?

I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.
I have variables copy1, copy2, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.
var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for(var i=0;i<4;i++){
console.log(copy+i);
console.log("copy"+i);
};
Ideally I would be able to select an element and style that via javascript.
Much appreciated
Thanks All.
Moe
Agree with #jaromanda-x:
var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for (var i=1; i<4; i++) {
console.log(window['copy'+i]);
};
Or you can use more simple example, like:
for (var i=1; i<4; i++) {
var name = 'copy' + i;
console.log(document.getElementById(name));
};
Or even:
for (var i=1; i<4; i++) {
console.log(document.getElementById('copy' + i));
};
You can store the properties in an object where values are set to the DOM element
let copies = {
1 : document.getElementById('copy1'),
2 : document.getElementById('copy2'),
3 : document.getElementById('copy3')
}
for (let [key, prop] of Object.entries(copies)) {
console.log(key, prop)
}
console.log(copies[1], copies[2], copies[3]);
Or use attribute begins with and attribute ends with selectors with .querySelector()
let n = 1;
let copy1 = document.querySelector(`[id^=copy][id$='${n}']`); // `#copy1`
let copy2 = document.querySelector(`[id^=copy][id$='${++n}']`); // `#copy2`
for (let i = 1; i < 4; i++) {
console.log(document.querySelector("[id^=copy][id$=" + i + "]"));
}
Since nobody has addressed your "certain number of characters" requirement yet, I thought I would.
You could always use jQuery or write your own $ method, which works as a document.getElementById() wrapper function.
Here is a jsfiddle to see it in action.
HTML
<div id="copy1">01234</div>
<div id="copy2">012345678</div>
<div id="copy3">0123456789 0123456789</div>
JavaScript
// Isn't this just a brilliant short-cut?
function $(id) {
return document.getElementById(id);
}
for (let i=1; i<4; i++){
let obj = $('copy' + i);
let value = (obj) ? obj.innerText : '';
console.log('value.length:', value.length);
};

how to access and sort 2d array in javascript

I'm writing a script to initalize 2d array in javascript by reading txt file. Here are some portions of my code
var neighbor = {};
var temp = new Array();
neighbor[nodemap[ temparray[0]]] = temp; //nodemap[ temparray[0]] is an integer
neighbor[nodemap[temparray[0]]]. push(nodemap[temparray[1]]);
neighbor[nodemap[temparray[0]]]. push(nodemap[temparray[2]]);
.... // continue to add value
Then I want to access and sort the array, like this
for (var i = 0; i < n_count; i++);
{
for (var k = 0; k < neighbor[i].length; k++);
neighbor[k].sort(function(a,b){return a - b})
}
However, I got the error that neighbor[i] is unidentified. Could you please show me how to fix that?
Your neighbor "array" is actually an object literal. So the way you should loop over neighbor is:
for (var key in neighbor) {
var cur = neighbor[key];
cur.sort(function (a,b) {
return a - b;
});
}

Finding an object and returning it based on search criteria

I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript).
Basically, I want to be able to search through an array of objects and return the object that has the information I need.
Example:
Each time someone connects to a server:
var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1);
function client_connection_info ( socket_id, ip_address, client_status) {
this.socket_id=socket_id;
this.ip_address=ip_address;
this.client_status=client_status; // 0 = offline 1 = online
};
Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example:
var results = SomeFunction(ip_address, object_to_search);
print_to_screen(results.socket_id);
I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly:
function where(array, predicate)
{
var matches = [];
for(var j = 0; j < array.length; j++)
if(predicate(j))
matches.push(j);
return matches;
}
Then you could simply call it like so:
var sample = [];
for(var j = 0; j < 10; j++)
sample.push(j);
var evenNumbers = where(sample, function(elem)
{
return elem % 2 == 0;
});
If you wanted to find a specific item:
var specificguy = 6;
var sixNumber = where(sample, function(elem)
{
return elem == specificguy;
});
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address'])
jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want.
var arr = [new_client, new_client2, new_client3]; // array of objects
var found; // variable to store the found object
var search = '127.0.0.1'; // what we are looking for
for(var i = 0, len = arr.length; i < len; i++){ // loop through array
var x = arr[i]; // get current object
if(x.ip_address === search){ // does this object contain what we want?
found = x; // store the object
break; // stop looping, we've found it
}
}

loop with array data

i have this code to get three values.
success: function(json){
$msg1 = parseFloat(json[0].valor1);
$msg2 = parseFloat(json[1].valor2);
$msg3 = parseFloat(json[2].valor3);
}
but now suppose that i need 200 values.
I'm not doing 200 times ...
$msg1 = parseFloat(json[0].valor1);
$msg2 = parseFloat(json[1].valor2);
$msg3 = parseFloat(json[2].valor3);
//...
$msg200 = parseFloat(json[199].valor200);
so, i need a loop, correct?
i tried something like this
for (i=0; i<200; i++) {
$msg(i+1) = parseFloat(json[i].valor(i+1));
i++;
}
but didn't work
thanks
This is why The Creator gave the world arrays.
var msgs = [];
for (var i = 0; i < 200; ++i)
msgs.push(parseFloat(json[i]['valor' + i]));
Note that your JSON data should also keep those "valor" properties as arrays, though in JavaScript you can deal with a bizarre naming scheme like that as in the example above.
edit — oops, typos fixed :-)
$msg = [];
for (var i=0; i<200; i++) {
$msg.push(parseFloat(json[i]["valor"+i]));
}
As stated by Pointy or:
var msgs = [];
for (i=0; i<200; i++) {
$msg[i] = parseFloat(eval('json[' + i + '].valor(' + i + '+1)'));
i++;
}
However eval is slow, so Pointy's answer is better.
var array = json.someid;// or json['someid'];
// json is returned not an array
var msgs = [];
$.each(array, function(index, e) {
msgs.push(parseFloat[e['valor' + index], 10);
});
when using parseFloat use the radix parameter unless you want bad things to happen;
javascript needs to be told for example not to parse octal;

Categories