I've been having problems with my code in JavaScript again. Here is the part of the code that I'm having trouble with and an explanation:
loadThis.onclick = function(){
localStorage.setItem("myName", storedTemporary[i].name);
}
deleteThis.onclick = function(){
this.parentNode.parentNode.remove();
storedTemporary.splice(storedTemporary[i], 1);
}
It splices it from the array and removes it from the screen. But let's say you have 3 items you delete the one and top and the bottom, when you try and load the last one in between it gives an error saying it can't setItem because it "cannot read property undefined". But the interesting thing is that when you console.log the current value of the localStorage item, "myName", it shows the last item's name. This is the for loop. I am using block scoping for it :
var storedTemporary = JSON.parse(localStorage.getItem("temporaryArray"))
for(let i = 0; i < storedTemporary.length; i++)
{
}
I am very confused. Please help.
Thank you,
Scratch Cat
Related
I have a realy hard problem that I couldn't find any solution in Internet
I used document.getElementsByClassName to access one HTML Element by It's class, my element is filterRow of dxDataGrid:
var filterRowElement = document.getElementsByClassName("dx-datagrid-filter-row");
console.log(filterRowElement);
console.log(filterRowElement.length);
My Problem is: The first console.log return HTMLCollection with length = 1 but the second return 0 (I tried to get length to access filterRowElement[0]).
I've tried console.log(filterRowElement[0]) and got undefined too
This is screen shoot:
I don't know why, it is the first time I got this problem
Please give me some advise. Thank you!
THANK YOU, I THINK MY PROBLEM IS DXGRID FILTERROW ELEMENT IS CONSECUTIVELY CHANGE SO I CAN'T ACCESS OLD ELEMENT
UPDATE
I don't know why but Using Jquery save Me (may be not alway true)
setTimeout(function () {
var getfilterRowElement = $(".dx-datagrid-filter-row");
console.log(getfilterRowElement[0]);
}, 3000);
Result:
Thank you so much
Updated: One reason why you might got a 0 for the second line, and a 1 for first line is: you print out filterRowElement.length, and it is true at that time, it was 0. When your event cycle is over, your framework (React, Angular, etc) updated the page (either after your actions or before your actions in the next event cycle). Now console.log prints out the whole structure and when you look at it in the debugger, now it is 1.
In order to solve this problem, I had to do something like this before:
setTimeout(() => {
doSomething();
}, 0);
So now you are waiting for the next event cycle so that your page is "constructed" or "updated".
If it is a static page, I was able to get 1 for both cases and able to access it:
Do you mean
console.log(filterRowElement);
gave you an object with length being 1, and then
console.log(filterRowElement.length);
gave you 0?
The following works:
arr = document.getElementsByClassName("foo-bar");
console.log(arr);
console.log(arr.length);
arr[0].innerHTML = "hello world";
arr[0].style.background = "orange";
arr[0].style.display = "inline-block";
arr[0].style.padding = "1.2em";
arr[0].style.borderRadius = "6px";
<div class="foo-bar"></div>
getElementsByClassName is live... is your page being changed meanwhile? Try document.querySelectorAll(".foo-bar") instead:
arr = document.querySelectorAll(".foo-bar");
console.log(arr);
console.log(arr.length);
arr[0].innerHTML = "hello world";
arr[0].style.background = "orange";
arr[0].style.display = "inline-block";
arr[0].style.padding = "1.2em";
arr[0].style.borderRadius = "6px";
<div class="foo-bar"></div>
I am new to js and hope this is not too trivial, but I am unable to find any help on the net.
I wish to output to console.log and prevent moving to a new line, so the next time the output will be appended to the same line. ie,
"use strict";
for (let i = 0; i<=9;i++){
console.log(i); // here i would like to freeze the output so the result is 0123456789 on one line, rather than those digits in a column.
}
I have seen fixes involving assigning the outputs to a string and printing in 1 hit, but that seems incredibly crude. Even in Fortran 4 as I recall in the '70s, you could prevent moving to a new line before printing again, so I think I am missing something fundamental. Also I cannot find any general help on formatting numerical output in javascript. Can someone point me in the right direction?
Thanks
Unfortunately, the console.log() method will only write out a string to a single line and doesn't support the appending behavior you are looking for.
As you detailed in your original post, you could accomplish writing the final result out through the use of a variable (i.e. displaying the final concatenated string), but not continually appending to the same line within the console itself as the loop is being iterated over.
Alternative Grouping Option
The concept of grouping entries is supported, which is obviously very different than your original ask, but it may be worth considering as mentioned in the documentation for console.group() and might look something like this:
var rollingConcatenation = '';
console.group("Looping Group Example");
for (let i = 0; i<=9;i++){
rollingConcatenation += i;
console.log(rollingConcatenation);
}
console.groupEnd();
This can give your console the following appearance, which can help with readability (depending on your use cases):
Do It Yourself Implementation
Another option might be to store your current console value within a variable and at clear it and rewrite the updated values out. Depending on your very specific use cases, you could achieve the behavior you are looking for using something like this crude implementation:
// Define a custom console
var customConsole = {
// Store a reference to your backing value
tempValue: '',
// Always write out the most recent value
log: function(msg) {
this.tempValue += msg;
console.clear();
console.log(this.tempValue);
},
// A clear method to clear the backing console
clear: function() {
this.tempValue = '';
console.clear();
}
}
for (var i = 0; i < 10; i++) {
// Use your custom console instead of the normal one
customConsole.log(i);
}
Take a new variable outside the loop and then prepare that string inside the loop and then you can console.log() outside the loop.
var str = '';
for (let i = 0; i <= 9; i++) {
str += i;
}
console.log(str);
I need to push value in array and stored in cookies when user click on GO button.
if value is more than 10 i need to remove the first added item in the array and updated cookies , displayed in front end.
but i'm tried multiple ways some time i am getting values sometimes not , the code is not consistently working.
please find below the code
var cookieName = 'orderList';
$scope.orderList = $cookies.getObject(cookieName) || [];
$scope.saveCookie = function (val) {
if ($scope.orderList.length >= 10) {
$scope.orderList.shift();
}
$scope.orderList.push({productName: val});
$scope.orderList = $cookies.putObject(cookieName,$scope.orderList);
}
Note : I am using angular 1.5 and cookie 1.5 version .and i am getting console error .
http://plnkr.co/edit/K17uJv72U2ytG6JHZBtn?p=preview
You didn't realize one thing. The error only appears when you click the button the second time.
The reason why you're getting this error is the last line in your code-
$scope.orderList = $cookies.putObject(cookieName,$scope.orderList);
when you replace it with -
console.log(typeof $cookies.putObject(cookieName,$scope.orderList));
you'll get undefined in the console. And that is the catch. When the function runs the second time, it is evaluating length of undefined, and hence, the error.
Just replace the line with $cookies.putObject(cookieName,$scope.orderList), because your $scope.orderList is already equal to the array with the new value pushed.
EDIT:
Updated Code
var cookieName = 'orderList';
$scope.saveCookie = function (val) {
$scope.orderList = $cookies.getObject(cookieName) || [];
if ($scope.orderList.length >= 10) {
$scope.orderList.shift();
}
$scope.orderList.push({productName: val});
$cookies.putObject(cookieName,$scope.orderList);
}
I brought the definition of $scope.orderList inside the function, since, in case the value of it is lost, it will reevaluate on each button click. Its not crucial in all cases. You might keep it out of the function, depending on your application flow.
New to Javascript, but I do have experience with Java and Python. I have looked at several other sites to see what's wrong with my code and I know that the error means that the property hasn't been initiated or does not contain anything, but I know I put something in there, so I think I might be getting Java and Javascript mixed up.
Here is my code:
var M=5;
var N=5; //where M and N can be changed if needed
var cellsNotChecked = [];
var startAt = [Math.floor(Math.random()*M), Math.floor(Math.random()*N)];
var path = [startAt];
//then make note of cells visited or not
for(i=0; i<M+2; i++){
cellsNotChecked[i]=[];
for(j=0; j<N+1; j++){
cellsNotChecked[j].push(i>0&&i<M+1&&j>0&&(i!=startAt[0]+1||j!=startAt[1]+1));
}
}
var cellsChecked= 1;
// now keep going until the number of cells checked outweighs the number of cells not checked
while(cellsChecked<cellsNotChecked.length){
//list of potential cells to go to next
var potential = [[startAt[0], startAt[1]+1], //right: y,x+1
[startAt[0],startAt[1]-1], //left: y, x-1
[startAt[0]-1,startAt[1]], //top: (top left hand corner is 0,0, so) y-1, x
[startAt[0]+1,startAt[1]]]; //bottom: y+1, x,
var neighboringCells = [];
//do things
cellsChecked++;
}
The error shows up at var potential = [[startAt[0], startAt[1]+1],... with startAt[0] being underlined all the way to after startAt[1]+1.
Like I said, I think I am giving it values, but I don't know how to check (am using Notepad++).
Edit notes
Added curly braces around first for-loop (thank you for catching that, Mupparthy Ravindranath), but error now occurs at cellsNotChecked[j].push(...).
Full error states: Uncaught TypeError: Cannot read property 'push' of undefined
Part of the problem that I am having is that it appeared to work yesterday before I added a completely un-related function. Now it doesn't work at all. Is it possible for Javascript code to get too long?
I'm getting a very weird undefined error:
function login(name,pass) {
var blob = Utilities.newBlob(pass);
var passwordencode = Utilities.base64Encode(blob.getBytes());
var ss = SpreadsheetApp.openById("");
var sheet = ss.getActiveSheet();
var data = sheet.getDataRange().getValues();
var i=1;
while (name != data[i][0]){
Logger.log(data[i][0]);
i++;
}
if (passwordencode == data[i][1]){
UserProperties.setProperties({
"name" :name,
"pass" : passwordencode
});
Logger.log("You are logged in");
}
else if (passwordencode != data[i][1]) {
Logger.log("You are not logged in");
UserProperties.setProperties({
"name" : "",
"pass" : ""
});
}
}
Using Google Apps Script. The one that's undefined is the while statement where while(name != data[i][0]) claiming that you cannot read property "0" from undefined. What's weird about this, If I remove the data[i][0] in the while statement, it still works in the logger.log. And everywhere else. What the heck is going on?
EDIT: If I change the while to a if statement it also works.
The while increments the i. So you get:
data[1][0]
data[2][0]
data[3][0]
...
It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.
Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.
Ammend your while statement to this...
for(var iIndex = 1; iIndex <= data.length; iIndex++){
if (data[iIndex][0] === name){
i = iIndex;
break;
};
Logger.log(data[iIndex][0]);
};
Check your array index to see if it's accessed out of bound.
Once I accessed categories[0]. Later I changed the array name from categories to category but forgot to change the access point--from categories[0] to category[0], thus I also get this error.
JavaScript does a poor debug message. In your case, I reckon probably the access gets out of bound.
For me, the problem was I was using a package that isn't included in package.json nor installed.
import { ToastrService } from 'ngx-toastr';
So when the compiler tried to compile this, it threw an error.
(I installed it locally, and when running a build on an external server the error was thrown)
Under normal circumstances,out of bound of array when you encounter the error.
So,check uo your array subscript.