How to set [i] in array? - javascript

I don't know to set [i] in the array.
statusResponse() {
var dataStatus = this.$.xhrStatus.lastResponse;
for(var i = 0; i < this.maxStatus; i++) {
console.log(this.maxStatus);
console.log([i]);
console.log(dataStatus);
console.log(dataStatus[fs_+ i +_P41001_W41001B]);
this.userInfo.status({
"branch_plant": this.$.xhrStatus.lastResponse.fs_ +
[i] +_P41001_W41001B.data.gridData.rowset[0].sDescription_99.value
});
}
}

You could change:
dataStatus[fs_+ i +_P41001_W41001B]
to
dataStatus["fs_" + i + "_P41001_W41001B"]
Explaination
This is roughly how the computer understands it the following line:
Take string "fs_"
Add the variable i to it, so the string become "fs_4" (if i = 4)
Add "_P41001_W41001B" to it, so the string becomes "fs_4_P41001_W41001B"
Get dataStatus["fs_4_P41001_W41001B"]
Updated code:
statusResponse() {
var dataStatus = this.$.xhrStatus.lastResponse;
for(var i = 0; i < this.maxStatus; i++) {
console.log(this.maxStatus);
console.log([i]);
console.log(dataStatus);
console.log(dataStatus["fs_" + i + "_P41001_W41001B"]);
this.userInfo.status({
"branch_plant": this.$.xhrStatus.lastResponse["fs_" + i + "_P41001_W41001B"].data.gridData.rowset[0].sDescription_99.value
});
}
}

Related

How do I display an array inside a string in javascript?

This is the code :
list = ["Alex","John","Kit","Lenny"];
for(var i = 0; i < 4; i++) {
$("body").append("<p> list[i] </p>');
};
Look at the for loop(yes this is using jquery),i want to add the list items inside the paragraph headers.How do i do it ?
list[i] is not a string, it's a variable. To include it into the appended element, close the quotation marks in following way:
var list = ["Alex","John","Kit","Lenny"];
for(var i = 0; i < 4; i++) {
$("body").append("<p>" + list[i] + "</p>")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Font Size changes according to count of word

function test(data) {
wordCount = {};
theWords = [];
allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i = i + 1) {
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
var result = "";
for (var i = 0; i < theWords.length; i = i + 1) {
result = result + " " + theWords[i];
$("theWords.eq[i]").css("fontSize", (wordCount.length + 50) + 'px');
}
return result;
}
console.log(test("MyWords"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm having troubles with the syntax of the line "$("theWords[i]......."
I realize how simple of a question this is, and not academic to the community, but I have been fumbling with this syntax for awhile and can't find any specific forum to correct my syntax error.
I am attempting to have the font size change according to the amount of times the word appears in a document.
wordCount = count of appears.
theWords = all words I would like to have the rule applied to
I manage to have something working with what you did using a bit more of jQuery to build the list of words to show. hope it helps :D.
$(document).ready(function() {
var data = $(".sometext").text();
wordCount = {}; theWords = []; allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i++){
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
for(var i = 0; i < theWords.length; i = i + 1) {
$('<span/>', {
'text': theWords[i] + " ",
'class': theWords[i]
}).appendTo('.result');
}
for(var i = 0; i < theWords.length; i++) {
$("." + theWords[i]).css("font-size", 15 + wordCount[theWords[i]]*5 + "px");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="sometext">javascript is a language that could be a language without such things as language but not without things as parenthesis. language is the bigest word here.</p>
<hr>
<div class="result"></div>

dat.GUI create multiple buttons with same name

I try to use dat.GUI to create multiple buttons all with same name "ShowCoord", is this possible? What I have currently is:
for (i = 0; i < overlay.numElements; i ++)
{
var length = overlay.elementNumVertices[i];
var subObj = {
'name' : overlay.elementNames[i],
'index' : i,
'numVertices': overlay.elementNumVertices[i],
"ShowCoord" : function(){
console.log("i is " + subObj['index']);
var verts = overlay.elementVertices[i];
for(var j = 0; j < subObj['numVertices']; j ++)
{
console.log("The coordinates are " + verts[3*j] + ", "+ verts[3*j+1] +", "+verts[3*j+2]);
}
}
};
subObjArray.push(subObj);
}
for(i = 0; i < subObjArray.length; i ++)
{
var currObj = subObjArray[i];
var subGui = gui.addFolder(currObj['name']);
subGui.add(currObj, 'numVertices');
subGui.add(currObj, "ShowCoord");
}
I now have the correct currObj['name'] and currObj['numVertices'] displayed. But all the "ShowCoord" button only contains information of the very last subObj (so console.log("i is " + subObj['index']) will print out 148 every time even if I click different button). How can I make it work? Thanks a lot!
Try moving subGui outside the for loop and modifiy you code so that you don't reassign subGui varialbe.
var subGui = new dat.GUI();
for(i = 0; i < subObjArray.length; i ++)
{
var currObj = subObjArray[i];
subGui.addFolder(currObj['name']);// <--- work on this line
subGui.add(currObj, 'numVertices');
subGui.add(currObj, "ShowCoord");
}
Otherwise it will always be redefined with the last iterated element of for loop
Note: This is just a hint, I can't conclude more from your code.

Comparring Arrays with For Loops

Alright so I have been working on this one for a bit. I'm comparing the values of two arrays using a For Loop. Every time the array known as cart hits a number that can be found in the products array, it displays the info of the products array, for each time it is hit. I think my code itself is fine ( though I could be wrong) but it's not displaying the values. So I think there's something wrong with my execution of said process there. The codes as follows
function Fill(){
var txt=""
var products = new Array();
products[0] = {name: "refrigerator" , price:88.99, img:"img/refrigerator.jpg"};
products[1] = {name: "microwave oven" , price: 76.99 , img:"img/microwave.jpg"};
products[2] = {name: "dishwasher" , price:276.67 , img:"img/dishwasher.jpg"};
var carts = new Array ();
carts[0]= 2;
carts[1]= 0;
carts[2]= 1;
carts[3]= 1;
carts[4]= 0;
carts[5]= 1;
carts[6]= 2;
carts[7]= 2;
for(var i=0; i < carts.length; i++){
for(var j = 0; j < products.length; j++){
if(carts[i] == j){
txt +=products[j].name + ' ' + products[j].price +" <img src='"+ products[j].img + "'>"
document.getElementById("answer").innerHTML += txt
}
}
}
}
Update answer with ES6:
const products=[{name:"refrigerator",price:88.99,img:"img/refrigerator.jpg"},{name:"microwave oven",price:76.99,img:"img/microwave.jpg"},{name:"dishwasher",price:276.67,img:"img/dishwasher.jpg"}];
const carts=[2,0,1,1,0,1,2,2];
const productsInCart = [...new Set(carts)]
.reduce((a,c)=>{
a.set(c,products[c])
return a;
}, new Map());
const res = carts.map(c=>{
const {name, price, img} = productsInCart.get(c)
return `${name} ${price} <img src="${img}"/>`;
}).join("");
document.body.innerHTML = res;
You should be comparing carts[i] with j otherwise you won't find anything
var txt = ""
var products = new Array();
products[0] = {
name: "refrigerator",
price: 88.99,
img: "img/refrigerator.jpg"
};
products[1] = {
name: "microwave oven",
price: 76.99,
img: "img/microwave.jpg"
};
products[2] = {
name: "dishwasher",
price: 276.67,
img: "img/dishwasher.jpg"
};
var carts = new Array();
carts[0] = 2;
carts[1] = 0;
carts[2] = 1;
carts[3] = 1;
carts[4] = 0;
carts[5] = 1;
carts[6] = 2;
carts[7] = 2;
for (var i = 0; i < carts.length; i++) {
for (var j = 0; j < products.length; j++) {
if (carts[i] == j) {
txt = products[j].name + ' ' + products[j].price + " <img src='" + products[j].img + "'>"
document.getElementById("answer").innerHTML += txt
}
}
}
<div id="answer"></div>
Your txt variable should be modified with = and not +=
You should optimize your code. document.getElementById("answer") could be initiated globally for example.
"carts" is an array of numbers (as per your source code) while "products" is an array of objects. So your condition "carts[i] == products[j]" will never fire.
What's the value of your appliance variable?
It'll cause the code to error out.
To also steal Alex's answer: "carts" is an array of numbers (as per your source code) while "products" is an array of objects. So your condition "carts[i] == products[j]" will never fire.
Perhaps this is better?..
carts[7]= 2;
for(var i=0; i < carts.length; i++){
txt +=products[carts[i]].name + ' ' + products[carts[i]].price +" <img src='"+ products[carts[i]].img + "'>"
document.getElementById("answer").innerHTML += txt
}
Upvoting Grimbode's answer as it's pretty close to mine, but cleaner.
I'm not sure why you need the second for loop. You're trying to compare a number with a product object by doing this and it will never work. OK, assuming that what you are trying to achieve is that if carts[0]=2 you want the info for products[2] then try something like:
for(i=0; i<carts.length; i++) {
if(i<products.length) {
currProd=products[carts[i]];
//Process the currProd object as you will
}
}

Finding min in a stack- Won't print out any result

Trying to find the min for this stack; however, whenever I run this in JSFiddle nothing prints out... anyone explain to me why? here's the code:
function min_stack() {
var min = 0;
this.elements = [];
this.push = function(element) {
this.elements.push(element);
}
this.pop = function() {
return this.elements.pop();
}
this.min = function() {
min = this.elements[0];
if (this.elements.length > 0) {
for(int i = 0; i < this.elements.length; i++) {
if (min > this.elements[i]) {
min = this.elements[i];
}
}
}
return min;
}
}
var myStack = new min_stack();
myStack.push(5);
myStack.push(4);
myStack.push(3);
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
myStack.pop();
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
myStack.pop();
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
There is a syntax error in your for which shows up immediately in browser console
Change:
for(int i = 0; i < this.elements.length; i++) {
TO
for(var i = 0; i < this.elements.length; i++) {
DEMO: http://jsfiddle.net/y7wET/
ALso as pointed out in comments I doubt you want to use print
int i = 0; is not valid JavaScript. JavaScript does not allow you to specify the type of a variable when declaring it; instead, use var i = 0;.
Also, because "window" is the global object, in the context of the Web page, print() is equivalent to window.print(), which prints the page to your printer.
For debugging purposes, you can pop up a message box using window.alert(); if that is too annoying, you could do something such as adding your output to a textarea element instead.

Categories

Resources