console gives a string isn't a function error - javascript

I'm creating a quiz and console shows a problem with split, that it's not a function, but it worked before. I've tried using toString method but it doesn't help, console says instead that can't read properties of null. If someone could help me, it would be appreciated.
let correctAnswer = document.getElementById("correct-answers");
document.querySelector(".check").onclick = function () {
/* Hide unneeded sections and showing scores */
quiz.classList.add("hidden");
correctAnswer.classList.remove("hidden");
/*Showing all previous scores */
const lastScore = localStorage.getItem("latestScore") || [];
const scoreDetail = lastScore.split(',');
scoreDetail.push(score);
localStorage.setItem("latestScore", scoreDetail);
let userScoreTemplate = `<h2>This Round's Score: ${score}</h2>`;
scoreDetail.map((items, index) => {
userScoreTemplate += `<h3>Score ${index}: ${items}</h3>`
});
let userScoreBoard = document.getElementById("user-score");
userScoreBoard.innerHTML = userScoreTemplate;

localStorage.getItem() will return a string.
You need adjust your code accordingly to default to a string in case the item is not defined:
const lastScore = localStorage.getItem("latestScore") || "";

In your code lastScore is an array, not a string, so the split method will not work on it. It works only on strings.You can use JSON.Parse like that. This will convert array data into javascript array.
const scoreDetail = JSON.parse(lastScore) || [];
scoreDetail.push(score);
And after that convert the array into a JSON string :
localStorage.setItem("latestScore", JSON.stringify(scoreDetail));

is latest score is a obj/array/string or what?
If it's an array/object then wrap localStorage.getItem in JSON.parse() so js can convert array data into js array

As per the error, You are trying to apply split on an array instead of a string.
Looks like, localStorage.getItem("latestScore") is undefined while you are trying to access it and it assigned an empty array to lastScore variable.
Hence, Instead of
const lastScore = localStorage.getItem("latestScore") || [];
Use
const lastScore = localStorage.getItem("latestScore") || "";

Related

How to get value on class and put into array JavaScript DOM?

I have some tables that have data and can using it on <td>. So more like it I have something like this (show on images below)
My Element
I want to get that all positions Name and put it into an array so I can make of use that array I tried to use this code and got undefined
script.js
/** Checking if There positions name */
function checkPositions(){
let positions = document.getElementsByClassName('check-positions').innerHTML;
let array = [];
array.push(positions);
console.log(array);
}
Then how can I get that value??
The problem that you have is that document.getElementsByClassName('check-positions') returns a HTMLCollection which does not have an innerHTML property.
What you need to do is convert the HTMLCollection into an array, and then read the innerHTML property for each of the items in the array. See the following example:
const elements = document.getElementsByClassName('check-positions');
const positions = Array.from(elements).map(element => element.innerHTML);
console.log(positions);
<div class="check-positions">1</div>
<div class="check-positions">2</div>
<div class="check-positions">3</div>
Use like this
let positions = document.getElementsByClassName('check-positions')[0].innerHTML;
It's showing none because u r fatching whole array and pushing it without using indexes
Code
function checkPositions(){
all_ele = document.getElementsByClassName('check-positions')
length = all_ele.length
let array = [];
for( let i=0;i<length;i++)
{
let positions = document.getElementsByClassName('check-positions')[i].innerHTML;
array.push(positions);
}
console.log(array);
you can use jquery code to do this.
var arr = [];
$("#tablePlacement tr").each(function() {
var name = $(this).children('td.check-positions').text();
arr.push(name);
});
You should use
let positions = document.getElementsByClassName('check-positions').innerText;

i got error : Cannot read property 'push' of null

I tried like this reference, but it did not work anyway.
This is a new thing for me, and just started learning javascript.
var getTbl = localStorage.getItem("tableList");
var resultTable = [];
if (getTbl !== undefined && getTbl !== '') {
resultTable = JSON.parse(getTbl);
}
let newtableHTML = addTable;
resultTable.push({
table: newtableHTML
});
// save the new resultFolder array
localStorage.setItem("tableList", JSON.stringify(resultTable));
i try something like this, but no luck :
var resultTable = resultTable || [];
Sorry if I'm wrong in trying that way.
The line
resultTable = JSON.parse(getTbl);
replaces the contents of the resultTable variable with whatever JSON.parse returns. Apparently JSON.parse is not returning an array (or other kind of object with a push method, but arrays are the only built-in ones that do).
My guess is that it's returning null, because getItem returns null if the key doesn't exist in local storage, but you're not checking for that. So you're passing null into JSON.parse, it gets coerced to string ("null"), and then parsed as JSON, yielding...null.
Since you're storing an array (and arrays are never falsy), I'd probably do this:
var getTbl = localStorage.getItem("tableList");
var resultTable = getTbl ? JSON.parse(getTbl) : []; // <====
let newtableHTML = addTable;
resultTable.push({
table: newtableHTML
});
// save the new resultFolder array
localStorage.setItem("tableList", JSON.stringify(resultTable));
That tests if what getItem gave us was falsy and, if it is, uses [] instead.
But there are a dozen variations on this theme. For instance:
var resultTable = JSON.parse(localStorage.getItem("tableList") || "[]"); // <===
let newtableHTML = addTable;
resultTable.push({
table: newtableHTML
});
// save the new resultFolder array
localStorage.setItem("tableList", JSON.stringify(resultTable));
Change the way 'resultTable' is initialised to :
resultTable = new Array();
So that data can be pushed properly to resultTable.

.slice() is not a function although called on string

I'm trying to figure out some collision, but the compiler keeps showing the error that .slice() is not a function. Here is the code:
var topPos1 = $('#player').css("top");
var rightPos1 = $('#player').css("right");
var topPos2 = $('#player').css("top");
var rightPos2 = $('#player').css("right");
var pos = topPos1.indexOf('px');
topPos1 = parseInt(topPos1.slice(0,pos));
My jQuery is loaded.
Maybe your topPos1 return nothing, if the $('#player') has no css value for top, assigning it to a value will result null or NaN.
You should use log the values to see if the result are correct.
you can't directly slice a number, you can convert it into string then slice after
like this:
topPos1 = parseInt(topPos1.toString().slice(0,pos));
You can just use .replace('px', '') - it will save you one function call

Javascript JSON stringify No Numeric Index to include in Data

i am trying to pass non numeric index values through JSON but am not getting the data.
var ConditionArray = new Array();
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
When i alert the Data Variable it has the Values 1,2 and 3 but module and table are not included. How can this be added so that the whole string is passed.
EDIT : And what if i have some multidimensional elements also included like
ConditionArray[0] = new Array();
ConditionArray[0] = "11";
JSON structure only recognizes numeric properties of an Array. Anything else is ignored.
You need an Object structure if you want to mix them.
var ConditionArray = new Object();
This would be an better approach:
var values = {
array : ["1", "2", "3"],
module : "Test",
table : "tab_test"
};
var data = JSON.stringify(values);
Since javascript array accepts numeric index only. If you want non numeric index,use Object instead.
var ConditionArray = {};
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
Here is the working DEMO : http://jsfiddle.net/cUhha/
According to the algorithm for JSON.stringfy (step 4b), only the (numeric) indices of arrays are stringified.
This is because Array does not contain your elements.
When you do this:
ConditionArray['module'] = "Test";
You actually add a property to the ConditionArray, not elements. While JSON.stringify converts to string only elements of the ConditionArray. For example:
var arr = new Array;
arr['str'] = 'string';
console.log(arr.length) //outputs 0
You need to use an Object instead of Array
If you change the first line to
var ConditionArray = new Object();
you will achieve the desired outcome.
If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API.
In the function you can now decide what to do with value of key is of a specific type.
this is the way how I solved this problem
Where tblItemsTypeform is array and arrange is de index of the array
:
let itemsData = [];
for(var i = 0; i <= this.tblItemsTypeform.length -1;i++){
let itemsForms = {
arrange: i,
values: this.tblItemsTypeform[i]
}
itemsData.push(itemsForms)
}
And finally use this in a variable to send to api:
var data = JSON.stringify(itemsData)

Using array returned by String.split

data = 'numbersXXXtext';
or
data = 'XXXtext';
var get = data.split('XXX');
var sum = get[1];
I would like get always "text". If data equals numbersXXXtext, the code works fine, but if data is XXXtext then get[1] is undefinded.
Does anyone know how I can solve this?
If there is only one occurrence of XXX in the string, the bit you want will always be the last item in the array returned by split. You can use pop to get the last item of an array:
var a = "numbersXXXtext";
var b = "XXXtext";
console.log(a.split('XXX').pop()); // "text"
console.log(b.split('XXX').pop()); // "text"
Try this:
var sum = get.length > 1 ? get[1] : get[0]
Strange, i just tried your code, and it's working. (http://writecodeonline.com/javascript/)
Are you sure you are not missing something?
data = 'numbersXXXtext';
//data = 'XXXtext';
var get = data.split('XXX');
document.write(get[1]);
document.write("</br>");
document.write(get);
document.write("</br>");
I didn't get undefined in neither of your strings
An alternative using substring:
var data = 'numbersXXXtext';
var value = data.substring(data.indexOf('XXX') + 'XXX'.length);

Categories