If I am trying to add a variable as a property I get the error:
"Uncaught SyntaxError: Unexpected token +"
So basically I am trying to add a variable from a loop as a property to JSON like this:
var tables = ["table1", "table2", "table3"];
for (var x = 0; x < tables.length; x++) {
var item = $database. + tables[x];
console.log(item);
}
If i use (") like this
var item = "$database." + tables[x];
It works, but it becomes a string (if that's the proper name) so I can not view the JSON objects.
Why is this happening and Is this even possible to do?
Thanks!
Try this:
for (var x = 0; x < tables.length; x++) {
var item = $database[tables[x]];
console.log(item);
}
If your $database is dynamic and you don't want to have a hard-coded array of table names, you can also use Object.keys():
var tables = Object.keys($database);
you can use bracket notation:
for (var x = 0; x < tables.length; x++) {
var item = $database[tables[x]];
console.log(item);
}
Related
Edit: Actually the logic is wrong here.
I solved it using Python3 with a dictionary that updates the last index at which a letter is seen. In dynamic programming lingo, it is similar to L.I.S (longest increasing subsequence).
If anyone knows how to solve this without using a dictionary, please comment because I learned DP in school and those lessons only used arrays so it should be possible with just arrays.
Original question:
I am trying Leetcode, 3. Longest Substring Without Repeating Characters.
I can solve this in Python making a 2D table for dynamic programming.
But in JavaScript which I am sort of new to, I am getting an error.
evalmachine.<anonymous>:41
var top = T[i-1][j]
^
TypeError: Cannot read property '1' of undefined
at lengthOfLongestSubstring (evalmachine.<anonymous>:4
My code:
/**
* #param {string} s
* #return {number}
*/
var lengthOfLongestSubstring = function(s) {
//empty string
if (s.length <= 0){
return 0
}
//initialize dict
var dict = {};
//initialize 2D table T
var T = new Array(s.length)
for (var i = 0; i<s.length; i++){
T[i] = new Array(s.length);
}
//base cases are diagonals
for (var i = 0; i < T.length; i++){
for (var j=0; j<T.length; j++){
if(i==j){
T[i][j] = 1;
}
else{
T[i][j] = 0;
}
}
}
//put base case in dict
//dict[s[0]]=1
for (var i=0; i < s.length; i++){
for (var j=i+1; j<s.length; j++){
var row_char = s.charAt(i);
var col_char = s.charAt(j);
if (row_char==col_char){
T[i][j] = 1;
}
else{
//console.log("j",j,T)
var left = T[i][j-1]
console.log(left)
var top = T[i-1][j]
console.log(top)
var bigger = Math.max(left,top);
T[i][j] = bigger + 1
}
}
}
//iterate each row to get max
var high = Number.MIN_SAFE_INTEGER;
for (var i = 0; i < s.length; i++){
if(T[i][s.length-1] > high){
high = T[i][s.length-1];
}
}
return high;
};
It is letting me fill the table with 0's and base case of 1 indexing like T[i][j] but then complaining about indexing like that to get the value which I don't understand.
I looked at this: How to get value at a specific index of array In JavaScript?
But it does not really say anything different.
On the first iteration of the loop following the //put base case in dict comment i is 0.
You're then attempting to access T[i-1][j], which is the equivalent of T[-1][j].
Because T doesn't have a -1 index, T[-1] resolves to undefined, upon which you attempt to access index [j] and you get the error you're seeing.
Im triying of get all element by class name but i cannot get
when i try to get a one lement this command works
document.getElementsByClassName('div1')[5].value
but this command not works
var i=0;
for ( i < 6; i++) {
x = document.getElementsByClassName('div1')[i].value ;
}
var elementHtml = x;
i obtain this error
SyntaxError: missing ; after for-loop condition index.html:9:16
ReferenceError: downloadDiv is not defined
i get this error also
****TypeError: document.getElementsByClassName(...)[i] is undefined[Saber más]
please somebody help me
=============================================================
i put the response thankyou for your answers
var i = 0;
var x = 0;
for(var i = 0; i < document.getElementsByClassName('div1').length; i++){
x = x + document.getElementsByClassName('div1')[i].value;
}
var elementHtml = x;
You have made a mistake in your for loop in relation to your question;
for (var i=0; i < 6; i++) {
x = document.getElementsByClassName('div1')[i].value;
}
var elementHtml = x;
So, here, I am trying to create a two dimensional array; an array of arrays. However, whenever I try to push a value to the nested array, I receive the error seen in the title. In these for loops, the 'b' array is full of a list of strings, which are all received in a certain format, and the code then breaks it up and pushes it to the values in the 2-D array for further working.
var c = []
for(var u = 0; u < b.length; u++){
c[u] = new Array(0);
for(var y = 0; y < b[u].length; y++){
c[u][y].push(b[u].substring(b[u].indexOf('\"'), b[u].indexOf(",")));
b[u] = b[u].substring(b[u].indexOf(',') + 1);
}
}
I've looked on the other solutions here on stackoverflow; Either I can't wrap my head around them, or they're not applicable here. I can't tell what's wrong here. Help, please.
var c = []
for(var u = 0; u < b.length; u++){
c[u] = new Array(0);
for(var y = 0; y < b[u].length; y++){
// NOT WORKING
// c[u][y].push(b[u].substring(b[u].indexOf('\"'), b[u].indexOf(",")));
// WORKING
c[u].push(b[u].substring(b[u].indexOf('\"'), b[u].indexOf(",")));
// WORKING
c[u][y] = b[u].substring(b[u].indexOf('\"'), b[u].indexOf(","));
b[u] = b[u].substring(b[u].indexOf(',') + 1);
}
}
As you already declare an array b as blank without any value var b = [].
So, b.length will be 0.
Then this condition for(var u = 0; u < b.length; u++) will not execute and code will not work.
Update :
So, you can directly use :
c[u].push(b[u].substring(b[u].indexOf('\"'), b[u].indexOf(",")));
I think the problem here is that you are trying to use .push on something that is already a value:
/**
* c is an array: []
*/
var c = []
for (var u = 0; u < b.length; u++) {
/**
* c[u] is a subarray: [u: []]
*/
c[u] = new Array(0);
for (var y = 0; y < b[u].length; y++) {
/**
* c[u][y] is a value, currently undefined: [u: [y: ??]]
*/
c[u][y].push(b[u].substring(b[u].indexOf('\"'), b[u].indexOf(",")));
b[u] = b[u].substring(b[u].indexOf(',') + 1);
}
}
For what you want, you use either of the following:
// Value (replace as needed)
var value = b[u].substring(b[u].indexOf('\"'), b[u].indexOf(","));
// Option 1
c[u][y] = value;
// Option 2
c[u].push(value);
I have a bunch of comma-separated values stored as strings in a JSON file. My aim is to split these values to populate a select element which is based on Selectize.js. Code (excerpt) looks as follows:
var options = {};
var attr_split = data.attributes['Attribute1'].split(",");
var options_key;
for (var i = 0; i < attr_split.length; i++) {
options_key = attr_split[i]
}
var options_values = {
value: options_key,
text: options_key,
}
if (options_key in options)
options_values = options[options_key];
options[options_key] = options_values;
$('#input').selectize({
options: options,
});
Although this seems to work, the output in the select element only shows the last iterations done by the for loop. As per here
and here, I've tried
for (var i = 0; i < attr_split.length; i++) {
var options_key += attr_split[i]
}
but this throws me undefined plus all concatenated strings without the separator as per the following example:
undefinedAttr1Attr2Attr3
When I simply test the loop using manual input of the array elements everything appears fine:
for (var i = 0; i < attr_split.length; i++) {
var options_key = attr_split[0] || attr_split[1] || attr_split[2]
}
But this is not the way to go, since the number of elements differs per string.
Any idea on what I'm doing wrong here? I have the feeling it's something quite straightforward :)
when you declare 'options_key' ,you are not initializing it.so its value is undefined .when you concatenate options_key += attr_split[i] .in first iteration options_key holds undefined.so only you are getting undefinedAttr1Attr2Attr3.
so declare and initialize options_key like.
var options_key="";
and in your loop
for (var i = 0; i < attr_split.length; i++)
{
options_key = attr_split[i]
}
Everytime you replace options_key with value of attr_split[i].so after the loop it will contain last element value.corrected code is
for (var i = 0; i < attr_split.length; i++)
{
options_key += attr_split[i]
}
Just change var options_key; to var options_key="";
The reason you are getting undefined is because you have not defined the variable properly.
Here is a working example
var attr_split = "1,2,3,4".split(",");
var options_key="";
for (var i = 0; i < attr_split.length; i++) {
options_key += attr_split[i]
}
alert(options_key);
var options_values = {
value: options_key,
text: options_key
}
alert(options_values);
I'm trying to double my string xyz to xxyyzz in JS but can't get it to return correctly. What am I doing wrong?
<script>
string=["xyz"];
for (var i=0;i<string.length;i++)
{
document.write(string[i]*2);
}
</script>
var string = "xyz".split('').map(function(s){return s+s}).join('');
I like doing it using array maps instead of for loops. It seems cleaner to me.
The correct way would be to add the strings together (concatenation) instead of using a multiply by 2 which won't work. See below:
<script type="text/javascript">
var string = ['xyz'];
for (var i = 0, len = string.length; i < len; i++) {
document.write(string[i] + string[i]);
}
</script>
A few problems:
You've declared string inside an array, giving string.length a value of 1 as that's the number of elements
You can't multiply strings, unfortunately. You need to concatenate them
Here's how I'd do it:
var string = "xyz";
var newString = "";
for (var i = 0; i < string.length; i++)
newString += string[i] + string[i];
document.write(newString);
You didn't declared a string, you declared an array of string with 1-length.
Your are multiplying position of array (string[i]*2), trying concatenating (string[i] + string[i]).
This should work:
var string = 'xyz';
for (var i = 0, len = string.length; i < len; i++) {
document.write(string[i] + string[i]);
}