there are many questions with nearly the same title with this errors. i read them but seems different.
If I use a string directly in the function historyDatabase, it works.
If i using the string in an array function historyDatabase, it works.
If I take the string from the config file, I can output it and it looks correct (I use the error function for this).
I don't understand why the string from config causes problems here, but the same string in plain text doesn't cause any problems. Any idea?
let player = "";
player = Engine.ConfigDB_GetValue("user", "localratings.save.searchplayerinput");
error("player = ---" + player + "---"); // this output is correct seeh
// const playerData = this.historyDatabase["seeh"]; // this works
// const playerData = this.historyDatabase[["seeh"]]; // this works
// const playerData = this.historyDatabase[player]; // this produce errors
// const playerData = this.historyDatabase[[player]]; // this produce errors
// const playerData = this.historyDatabase[{player}]; // this produce errors
const playerData = this.historyDatabase[player]; // this produce errors
its part of this source https://gitlab.com/sl5net/LocalRatings/-/commit/891696adebcdd9fffbfce0a889808a3742e8992d used in a open-source game.
The error-screenshot
the hard-coded example string was implicitly converted into an object.
the example array was implicitly converted to an object.
but the string from the text file was not automatically converted.
I do not know why.
the solution was to pass the string from the config file as an object.
let playerObj = {};
playerObj = Engine.ConfigDB_GetValue("user", "localratings.save.searchplayerinput");
const playerData = this.historyDatabase[playerObj];
Related
i need when i click on input then must prompt and result transferred to storage, help me please, i tried to find this resolve in google but no use:(
const output = document.querySelector('[data-output]');
const LOCAL_STORAGE_LIST_KEY = 'task.lists';
const LOCAL_STORAGE_SELECTED_LIST_ID_KEY = 'task.selectedListId';
let lists = JSON.parse(localStorage.getItem(LOCAL_STORAGE_LIST_KEY)) || [];
let selectedListId = localStorage.getItem(LOCAL_STORAGE_SELECTED_LIST_ID_KEY);
output.addEventListener('click', e => {
let txt = prompt('Enter what you want to do ^^').toString();
lists.push(txt);
saveAndRender();
});
Your error seems to be in the renderLists function, which is on the JSFiddle that you linked in the comments. You're looping over your lists Array, which contains the input String - But you're trying to access properties as if it was an Object; which is instead giving you undefined
You have createListwhich will turn that input into an Object with the current keys, so I assume you meant to include that
output.addEventListener('click', e => {
let txt = prompt('Enter what you want to do ^^').toString();
lists.push(createList(txt));
saveAndRender();
});
Here is an updated JSFiddle
I need to send an email that contains the console.log output of a JS object. Here a code example:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
console.log(array_multi);
In my console result like this:
Is there some method to get this output in plain text, or should I write a custom parsing function?
If you are using JSON.stringify, you'll get the complete data, however there are a few downsides:
Arrays string properties, functions and other data structures get ignored completely (therefore serializing your data as is won't work¹)
circular references fail to serialize
There is no way to see inheritance from that
In your case you could do:
let array_multi = {};
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
// logs as object
console.log(array_multi);
console.log(typeof array_multi);
// parse and convert to string
console.log(JSON.stringify(array_multi));
console.log(typeof JSON.stringify(array_multi));
In Node.js you've got another option, which is util.format, which will return the same content as a string that you can see in the Node.js console. While it does give you a great insight into the different datatypes and relationships, it cannot show you the same infinite tree that an interactive console is able to show, so it will only show you a small part of the big picture.
¹: Your array_multi should actually be an object, not an array, as arrays should only have numeric keys.
After a lot of search the right method is write a custom function (chrome have once inside dev tools core)
here the solution:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
function print_js_element(elm, show_content = false){
let output_res = "{\n";
let object_keys = Object.keys(elm);
object_keys.some(function(key,index) {
output_res += "\t" + key + ": (" + elm[key].length + ")";
if(show_content){
output_res += " " + JSON.stringify(elm[key]);
}
output_res += "\n";
});
output_res += "\n}";
return output_res;
}
console.log(print_js_element(array_multi,false));
console.log(print_js_element(array_multi,true));
Covert this array into an object first:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
let arrObj = {...array_multi};
console.log(JSON.stringify(arrObj));
I'm trying to make write a node program that will read a file director and filter out those without a certain file extension. (This is a challenge for learnyounode) For some reason it adds to the list 'undefined'. Can anyone tell me why?
var fs = require('fs')
var path = process.argv[2];
var ext = process.argv[3];
var fileList = fs.readdir(path, function callback(err, list){
if (err){
throw err;
}
var filteredList = list.filter(function(fileName){
var extRx = new RegExp('\.' + 'md' + '$');
return extRx.test(fileName);
});
console.log(filteredList.forEach(function(val){console.log(val)}));
});
Outputs:
ACTUAL EXPECTED
"CHANGELOG.md" == "CHANGELOG.md"
"LICENCE.md" == "LICENCE.md"
"README.md" == "README.md"
"undefined" != ""
"" !=
This looks like it's actually an artifact of your console approach. You're console logging each element in the filtered list, and then console logging the output of the forEach function. The forEach function does not have a return value, so it's returning 'undefined' which your outer console log then logs.
Consider changing your console log to just:
console.log(filteredList);
You didn't include a runnable example so it's impossible to tell you what's wrong with the code that you didn't include, espacially when you don't even include the actual list of files that you're trying to filter.
See this example:
var list = [
"CHANGELOG.md",
"LICENCE.md",
"README.md",
"undefined",
"",
];
var filteredList = list.filter(function(fileName){
var extRx = new RegExp('\.' + 'md' + '$');
return extRx.test(fileName);
});
console.log(filteredList);
This correctly filters out the values that you want.
Change your program to have one console.log statement to make sure that you know what is being printed:
console.log(filteredList);
or:
console.log(JSON.stringify(filteredList));
One advice - don't complicate it so much:
var filteredList = list.filter(function(fileName){
var extRx = new RegExp('\.' + 'md' + '$');
return extRx.test(fileName);
});
when all you need is:
var filteredList = list.filter(name => name.match(/\.md$/));
You will have less trouble debugging your code if you keep it simple.
Update
After reading the comments I see that the 'md' is just a placeholder and you're using command line arguments in the real code. In that case I would use escape-string-regexp to escape the string. See:
https://www.npmjs.com/package/escape-string-regexp
When you use the escape-string-regexp:
var escape = require('escape-string-regexp');
You can do something like:
var extRx = new RegExp('[.]' + escape(ext) + '$');
where ext is the file extension that you got as a command line argument.
The [.] here is just my personal preference of writing a literal dot in regexes, I think it's more readable but it doesn't change any behavior here. The escaping is more important.
If you don't escape the string because you'd like your users to be able to use a custom regex instead of literal strings, then you should at least wrap the new RegExp() call in try/catch because it can throw exceptions on invalid regex syntax.
I have the following code javascript code
var tasksPlayed = [];
tasksPlayed[90] = true;
var json = JSON.stringify(tasksPlayed);
var output = JSON.parse(json);
this gives an error
SyntaxError: JSON.parse
Im not sure why, if I do a .toSource() on the objects I get
keyValue:"[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,true]"})
Any ideas where I might be going wrong
I don't get this error when I run the code, but the thing with the null values is that tasksPlayed is an array, so when you set tasksPlayed[90] = true;, then it automatically fills all positions from 0 to 89 with null. Try using a plain object instead of an array:
var tasksPlayed = {};
tasksPlayed[90] = true;
var json = JSON.stringify(tasksPlayed);
var output = JSON.parse(json);
I currently have a block like this defining some vars
var slider_1 = document.querySelector('#slider_1');
var slider_2 = document.querySelector('#slider_2');
...
And func's that take ID's like this:
function updateFromInput(id){
if(id==1){
var x = input_1.value*1;
x = Math.round((x*ratio)-offset);
slider_1.x.baseVal.value = x/scale;
}else if(id==2){
var x = input_2.value*1;
x = Math.round((x*ratio)-offset);
slider_2.x.baseVal.value = x/scale;
}
};
I am trying to refactor a bit.
I'm thinking that if I could, instead, instantiate my vars with dots rather than underscores like
var slider.1 = document.querySelector('#slider_1');
var slider.2 = document.querySelector('#slider_2');
then I'd be able to better utilize the ID already getting passed into my func's and eliminate tons of duplication.
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale; rather than having to have that code in each of the IF/ELSE conditions.
When I try that though, I get an error saying " Uncaught SyntaxError: Unexpected number ".
How should this be done?
You can't use a plain numeric key in an object.
You can do this, though:
var slider = {}; // or = [], if array syntax is more appropriate
slider[1] = ...
slider[2] = ...
Furthermore, the syntax you suggested isn't allowed if the key is actually a variable rather than a literal token.
In your example slider.id actually refers to the object with literal key id, not whatever value the variable id happens to have.
You have to put the variable inside square brackets, i.e. slider[id], so your function would be written thus:
function updateFromInput(id){
var x = +input[id].value;
x = Math.round((x*ratio)-offset);
slider[id].x.baseVal.value = x/scale;
};
You can't. The . is an invalid character for a variable identifier.
You can use it in object properties though.
var sliders = {
"slider.1": document.querySelector('#slider_1'),
"slider.2": document.querySelector('#slider_2')
};
Then use the square bracket version of the member operator to access the property.
alert( sliders["slider.1"].id );