A way to set property of array contents? - javascript

I've got an inventory script that I'm using to create a readout of the players inventory from an array. I need to set a .amount property, but I'm getting some undefined errors when I try to set them like this. I can't use sets or hashmaps. Can anybody tell me what I'm missing?
I'm using NaN only to debug the code at the moment.
//This is already defined as an array, just a shortcut.//
var inv = state.history[0].variables.player.inventory;
inv[i].amount = 0;
//Do this for every item in the inventory.//
for (var i = 0; i < inv.length; i++) {
//If the inventory item is Apple should resolve to ...inventory.Apple.amount.//
var q = inv[i].amount;
//If we find a duplicate in the array, just count and keep going.//
if (inv[i] == inv[i-1]){
q = (q + 1);
//If the item is the last one or unique, print the item on the inventory screen.//
} else {
q = (q + 1);
alert(inv[i] + " " + q.NaN);
new Wikifier(place, inv[i] + " " + q.NaN + "<br>");
}
}

You are trying to get i before it is defined in the loop, put it after:
//This is already defined as an array, just a shortcut.//
var inv = state.history[0].variables.player.inventory;
//Do this for every item in the inventory.//
for (var i = 0; i < inv.length; i++) {
inv[i].amount = 0;
//If the inventory item is Apple should resolve to ...inventory.Apple.amount.//
var q = inv[i].amount;
//If we find a duplicate in the array, just count and keep going.//
if (inv[i] == inv[i-1]){
q = (q + 1);
//If the item is the last one or unique, print the item on the inventory screen.//
} else {
q = (q + 1);
alert(inv[i] + " " + q.NaN);
new Wikifier(place, inv[i] + " " + q.NaN + "<br>");
}
}

Related

how to list all local storage on page properly in javascript?

I am trying to show all my localstorage items value on my index page but for some reason it is not showing. can anyone see what I am doing wrong in my code below. In my index page script I am looping thorough the length of local storage and trying to display them on screen, only thing that display is one item. Please help. thanks for your help.
here is my code (index page script):
document.addEventListener("DOMContentLoaded", function (event) {
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
})
The other script where I load it to localStorage:
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candsId');
var getCandId = document.getElementById("candsId");
var displayCandId = candidateId.options[candidateId.selectedIndex].value;
var id = 1;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText))
id += 1
localStorage.getItem(`key${id}`);
window.location = "/";
}
"key${id}" is a template string, you need to use backticks `` instead of quotation marks "".
You could also loop through localStorage as you normally would for most JavaScript objects:
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) { // ignore the prototype methods
// Do whatever you want with key and value found here
console.log(key + ": " + localStorage[key]);
}
}
Typo: Use i instead id
var dataFromLocalStorage = localStorage.getItem(`key${id}`);
correct:
var dataFromLocalStorage = `localStorage.getItem("key${i}");
Another thing, You are updating same innerHTML
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
// do something with localStorage.getItem(localStorage.key(i));
// missing template string 'key${id}'
var id = 1;
function addTheEvent() {
var showText = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText));
id += 1;
window.location = "/";
}

Limit items in ajax request

I am requesting data from a json to fill a table. I want to limit to 5 the request.
jQuery.getJSON("data/data.json", function(data) {
var table = $("table");
$.each(data, function(id, elem) {
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
});
})
Or another option is to add boolean key "active" to the data and that it brings me the data items with the value = true. How do i do this?
You can use .slice() to filter the returned array down to just the first 5 elements.
data = data.slice(0, 5);
Just use a simple for loop.
var json_arr, limit;
limit = 5; // set limit to whatever you like
json_arr = JSON.parse(json_data);
for(var i = 0; i < limit; i++;) {
var this_item = json_arr[i];
table.append(this_item); // do your thing
}
The best limit you can implement is on your own controller (where you get your data from)
But if you don't have access/don't want to change, you can simple achive this by JavaScript:
var limit = 5; //your Limit
for(var i in data){
if(i > limit) break;
var elem = data[i];
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
}

How do you generate a previous and next button for an array?

I have a function with this specific array in it.
var elementsArray = xmlDocument.documentElement.getElementsByTagName('track');
// console.log(elementsArray);
var arrayLength = elementsArray.length;
var output = "<table>";
for (var i=0; i < arrayLength; i++)
{
var title = elementsArray[i].getElementsByTagName('title')[0].firstChild.nodeValue;
var artist = elementsArray[i].getElementsByTagName('artist')[0].firstChild.nodeValue;
var length = elementsArray[i].getElementsByTagName('length')[0].firstChild.nodeValue;
var filename = elementsArray[i].getElementsByTagName('filename')[0].firstChild.nodeValue;
console.log(title + ' ' + artist + ' ' + length + ' ' + filename);
output += "<tr>";
output += ("<td onclick='songSelect(\"" + filename + "\")'>" + title + "</td><td>" + artist + "</td>");
output += "</tr>";
}
With this array how would i generate a previous and next button to move.
http://jsfiddle.net/xbesjknL/
Once could use a linked list or even the notion of C-like pointers that point at the prev/curr/next tracks. But alas this is Javascript and the client side is too processing burdened.
So you could just build your own simplified idea of pointers in a cursor like object that is constantly pointing at the current track's index, the previous track's index and the next. And you'd call the refresh method everytime the user clicks the prev or next buttons to update the cursor's pointers accordingly.
var cursor = {
prev:(elementsArray.length-1),
curr:0,
next:(1 % (elementsArray.length-1)),
refresh: function(button){ //button is either the btnPrev or btnNext elements
if (button.getAttribute("id") === "btnPrev") {
old_curr = this.curr;
this.curr = this.prev;
if ((this.curr-1) < 0)
this.prev = elementsArray.length-1;
else
this.prev = this.curr - 1;
this.next = old_curr;
} else {
old_curr = this.curr;
this.curr = this.next;
if ((this.curr+1) > (elementsArray.length-1))
this.next= 0;
else
if (elementsArray.length === 1)
this.next = 0;
else
this.next = this.curr+1;
this.prev = old_curr;
}
}
};
// example usage:
cursor.refresh(btnPrev);
elementsArray[cursor.curr]; // gives the previous track, which is now the current track
You can even simplify this even more by just keeping track of only the current track. Note

Pass value to nested parse.com query callback

So, using parse.com, I'm doing some nested queries... basically, getting an object and then retrieving its relations and doing some operations.
pageQuery.find({
success: function (results) {
var pages = [];
for (var result = 0; result < results.length; result++) {
var resArrayLength = pages.push(results[result].toJSON());
var indexOfLastPush = resArrayLength - 1;
console.log("resArrayLength = " + resArrayLength);
pages[indexOfLastPush].scrapeRules = new Array();
console.log("index of last push set to " + indexOfLastPush);
var relation = results[result].relation("RulesForPage");
//get the related scrape rules
relation.query().find({
success: function (rules) {
console.log("Found " + rules.length + " rules");
for (var i = 0; i < rules.length; i++) {
console.log("rule index = " + i);
console.log("Found rule " + rules[i].id);
pages[indexOfLastPush].AllRules = new Array();
pages[indexOfLastPush].scrapeRules.push(rules[i].id);
console.log("pushed rule " + rules[i].get("name") + " to page at index " + indexOfLastPush);
}
}
});
}
The problem I am seeing is that I am trying to indexOfLastPush to track an array index I need, but that value has changed by the time the call back has happened.
How can I pass it to the "success" callback so I have the index I need?
UPDATE: Thanks to #cggaurav for the excellent tip. Why does it seem like the answer to every JavaScript problem is to wrap your code in an anonymous function?
You have to have what is called a closure or an anonymous function for every relation.query() you make. See "More on lexical scoping" | http://mark-story.com/posts/view/picking-up-javascript-closures-and-lexical-scoping

Listing localstorage

I did my own feature using this:
function save(title, url)
{
for (var i = 1; i < localStorage.length; i++)
{
localStorage["saved-title_" + i + ""] = title;
localStorage["saved-url_" + i + ""] = url;
}
}
function listFavs()
{
for (var i = 1; i < localStorage.length; i++) {
console.log(localStorage["saved-fav-title_" + i + ""]);
}
}
save() happens when someone clicks on this:
onclick="save(\'' + title + '\', \'' + tab.url + '\');"> ' + title + '</a>';
However... it doesn't show the saved localStorages, how am I supposed to make it work?
Might it be because you are using the key 'saved-title_' + i to save the value and 'saved-fav-title_' + i to retrieve it?
The difference is the fav- part.
And your enumeration of the localStorage is bound to create errors as there is no guarantee that all items in it have a key that matches the pattern provided 'saved-fav-title_' + i - actually it is guaranteed to not be so as you are yourself inputting items with keys in the form of 'saved-url_'+ i.
So, if you want to properly enumerate the items with a key matching a pattern use
function listFavs(){
var key;
for (var i = 0, len = localStorage.length; i < len; i++){
key = localStorage.key(i);
if ((/^saved-fav-title_/).test(key)) {
console.log(localStorage.getItem(key);
}
}
}

Categories