Trying to number objects in jQuery - javascript

I'm trying to number objects, which can be added to a cart with drag'n'drop. So, this snippet should check the current number written in span.amountVal, and easily add ´+1´ to this number, but the result is always ´1´. When I uncomment the ´alert(i++);´, the snippet work like I want to. I'm confused, what is this about?
$.favList.find("div[data-asset-id="+ _itemID +"]").each(function() {
var i = $(this).find("span.amountVal").text();
// alert(i++);
$(this).find("span.amountVal").text(i++);
});
Thank you.

i++ first returns the value of i, then increments it. When you have the alert( i++ ) in place, the variable is already once incremented.
Put the ++ in front of the variable:
$(this).find("span.amountVal").text( ++i );
Or simply add one to it since you're discarding the variable right after:
$(this).find("span.amountVal").text( i + 1 );

you have a pre-increment/post-increment issue, the following change should solve it:
$.favList.find("div[data-asset-id="+ _itemID +"]").each(function() {
var i = $(this).find("span.amountVal").text();
$(this).find("span.amountVal").text(++i);
});
Pre-Increment adds one to i and then returns i while Post-Increment adds 1 to i after it has been returned.
Below is a similar post on StackOverflow touching on the topic:
post increment vs pre increment - Javascript Optimization

What are you guys doing? It SHOULDN'T read a SPAN's value, it's bad practice. Instead, it should read the items length (inside an object, for example) and then display it.

Related

How to change the final array to the front in JavaScript?

The case is:
function trocaPrimeiroEUltimo(array) {
array.array[0]
array.array[array.length - 1]
return array
}
I did this way, but it didn't work. I can't change the structure of the function, just what it's inside. Someone, could please help me?
Do you want to replace the last value with the first value?
if so, do:
temp = array[0]
array[0] = array[array.length-1]
array[array.length-1] = temp
That's a simple swap.
The syntax makes use of new ES6 capabilities (destructuring an array). This way the exchange can be done without a temporary variable.
The whole thing can even be done as a one-liner:
const arr=[7,8,9,10,11];
const swapFirstLast=(a,l)=>([a[0],a[l]]=[a[l=a.length-1],a[0]],a);
console.log(swapFirstLast(arr))
The use of the argument l is also something you probably would not do in a "real" application. I only went for it so I would not have to define the variable locally. l is assigned a value on the right hand side of the assignment expression. By the time the result needs to be stored l has been calculated and can also be used for addressing the right target element.

How to Check the variable value is [""] in JavaScript

Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.

$.each index initial value

As we know the index of $.each will start from zero. I want to print the index from 1 to 10, as I have 10 array.
$.each(myArr, function(i){
console.log(i++);
}
why is it I'm getting from 0 still?
Try this.
$.each(myArr, function(i){
console.log(++i);
})
This is a difference between prefix and postfix operator. Prefix operator increases the value after the current operation is done. Postfix operator increases the value first and executes the current statement. This above code is for just explaining things.
As #Ghazgkull suggested, it is better to use i+1 which conveys the indent of the code.
The ++ operator AFTER the variable increases that variable after the current call is finished (in your case, after the console log call), which is why you see it starting from 0.
Since it's an index, there's no need for you to manually increase its value, but a simple console.log(i+1); would work just fine.
Otherwise, you can increase it BEFORE the current call, by putting ++ before the variable, as #Satya said in the comments.
See it here:
var myArr = [1,1,1,1,1,1,1,1,1,1];
$.each(myArr, function(i){
console.log(i+1);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
When the ++ operator is applied on the right side of the variable (i++), the current value before incrementing is used. You should use ++i if you want to get the value after incrementing.
$.each() increments the value for you. You don't need to increment it yourself. Your code should be:
$.each(myArr, function(i) {
console.log(i + 1);
}
Even if ++i works in this case, you shouldn't use an incrementor here. To any experienced programmer, it will look like you're trying to increment a value in a way that doesn't make sense. Using i + 1 makes it clear that you're simply computing a value.

How do I retrieve a key from a JSON response, when I don't know the key value?

This may be really simple, but I've beat my head against the wall trying to figure it out.
I need to grab a value from a JSON response, but the key returned in the response is random, so I can't directly reference it to drill into it.
Here's the response I'm getting back:
var c = {
"success": {
"7d40ab5352b0471cae5bdefc2e032840": {
"__type__" : "user",
"__id__" : "7d40ab5352b0471cae5bdefc2e032840"
}
},
"errors": {}
}
What I need is the random string you see there - the ID. I've tried all kinds of things, and cannot for the life of me figure out how to get the ID back as a string. I've tried getting at it with array notation c.success[0][0] to no avail. Obviously, I can't use dot notation, since I don't know what to put after .success.
Anyone know what to do in a situation where the keys of the array aren't known beforehand? I want to make sure that I do this in a way that's considered the best practice, not a hack.
Thanks...and if I've somehow missed an answer to this that's otherwise published, please send me that way. I've searched for days and can't find this answer.
This:
var obj = c.success[ Object.keys( c.success )[0] ];
obj.__type__ // "user"
obj.__id__ // "7d40ab5352b0471cae5bdefc2e032840"
Live demo: http://jsfiddle.net/AJaBS/
for (var prop in c.success) {
alert(c.success[prop].__id__); // Replace the alert with whatever you want to do with the ID
// break; // Uncomment if there can be more than one ID returned and you only want one
}
and if the key is the same as the __id__ value, you can simply do:
for (var prop in c.success) {
alert(prop); // Replace the alert with whatever you want to do with the ID
// break; // Uncomment if there can be more than one ID returned and you only want one
}
Although Šime Vidas's use of Object.keys is more elegant, you will need the above code to work in older browsers unless you use what is called a him (i.e., you add some extra code which lets you use new standards today--i.e., an implementation of Object.keys which does the same thing as I did above, unless a built-in version already exists, in which case the shim will give preference to the built-in version).
You can use a simple loop:
for (var id in c.success) {
var obj = c.success[id];
// do something
}
If you want to ensure that only the first property in the object will be handled, you can add a break; statement in the end.

How to Efficiently Update Objects in Javascript

I'm working on a javascript game for fun, where I have an array of character objects. I'm periodically doing checks on fields within the objects, (like characters[i].xpos, characters[i].ypos, and so on). Is it more efficient to add a function to the prototype of the class to handle moving left and right, and call that periodically, or more efficient to have a global function that adjusts the x and y pos of the character object?
Thanks for your help guys!
Edit:
Thanks for your answers guys. I'll try to be more specific. I have one global update function that is called with an interval and has a bunch of code in it that changes the properties of an object, like:
globalupdate() {
characters[i].posx++;
characters[i].posy++;
... and more code like that
}
Would it be faster to just write a prototype function within that class and call that? Like:
globalupdate() {
characters[i].update();
}
Thanks for all the quick replies!
I have just read an article on that subject by John Resig (author of jQuery). Judging from that, the most important thing is to not have multiple timers (i.e. intervals and timeouts) because there is a potential for conflict.
So, if your global function will result in having less timers this might very well be beneficial to the overall performance.
link: http://ejohn.org/blog/how-javascript-timers-work/
Edit: Do I understand your update correctly and is this what you want to know: given a block of code,
{
object1.<key> = <value> ;
object2.<key> = <value> ;
/* ... */
objectN.<key> = <value> ;
}
and an alternative block of code,
{
object.prototype.change = function( ) { this.<key> = <value> ; } ;
list = [object1,object2,/* ... */,objectN] ;
for(i = 0 ; i < list.length ; i++) list[i].change( ) ;
}
which one would be executing faster?
As for all performance questions where it only takes 1 min to code together a test for each case, try.
I think the difference is negligble compared to the "visible" part of the update, ie updating the DOM etc. Also remember that it's probably going to be differences depending on which browser that is used.

Categories

Resources