Javascript Can't use array content as array index? - javascript

When I trird to run the js code, it always said "Uncaught TypeError: Cannot read property '_id' of undefined" for
deployedID.push(data[j]._id);
So after some thinking, I believe the problem lies in
var j = deploy[i];
Is there any way to solve it? Thanks in advance.
Below is the complete code:
var deploy = [];
var deployedID = [];
var deployedename = [];
var deployedoname = [];
var deployedrank = [];
function popularizeTable(){
$.get("/SSS/getlist", function(data){
deploy = randomunique(data.length ,100);
for (var i = 0; i < 100; i++){
var j = deploy[i];
deployedID.push(data[j]._id);
deployedename.push(data[j].ename);
deployedoname.push(data[j].oname);
deployedrank.push(data[j].rank);
}
var str = " ";
var k = 0;
for (var i = 0; i < 5; i++){
str += "<tr>";
for(var j = 0; j < 20; j++){
str += "<td><section id=\"" + deployedID[k] + "\" class=\"container\"><div class=\"card\">"
str += "<figure class=\"front\"><img src=\"images/back.jpg\"></figure>";
str += "<figure class=\"back\"><img src=\"images/Clear/" + deployedename[k] + "/001.jpg\"></figure></div></td></section>";
k++;
}
str += "</tr>";
}
$("#table").append(str);
});
}
$( document ).ready(function() {
popularizeTable();
$(document).on("mouseover", ".card", function(){
$(this).toggleClass("flipped")});
});
function randomunique(max, num){
var uniquelist = [];
for (var j = uniquelist.length; j < num; j++){
var i = parseInt(Math.random() * (max - 1) + 1);
if (uniquelist.indexOf(i) == -1){
uniquelist.push(i);
}
}
return uniquelist;
}

Related

How can I use a variable in String.fromCharCode()?

I am trying to get the code below to convert the unicode into a string but have no luck, please help?
function rot13(str) {
var message = "";
for (var i = 0; i < str.length; i++) {
message += str.charCodeAt(i) + " ";
}
message = message.split(" ").filter(Boolean).join(",");
return String.fromCharCode(message);
}
console.log(rot13("Hello World"))
fromCharCode("1,1,1,1") is not the same thing as fromCharCode(1,1,1,1) you need to use apply with an array.
function rot13(str) {
var message = "";
for (var i = 0; i < str.length; i++) {
message += str.charCodeAt(i) + " ";
}
message = message.split(" ").filter(Boolean);
return String.fromCharCode.apply(String, message);
}
console.log(rot13("Hello World"))
You want something like this:
http://buildingonmud.blogspot.com/2009/06/convert-string-to-unicode-in-javascript.html
function toUnicode(theString) {
var unicodeString = '';
for (var i = 0; i < theString.length; i++) {
var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
unicodeString += theUnicode;
}
return unicodeString;
}
console.log(toUnicode("Hello World"));

adding inputs in for loop

I have code like that https://jsfiddle.net/Lcfnxxtv/ and i'd like to labels look like that eg.
Number of children
ages 5 - 18"
I want it in two separate lines and NOT all in one line(of course, if it's possible) 'Number of children ages 5 - 18' but i don't know how to do this in my code.
jQuery(document).ready(function() {
var array1 = [];
var array2 = [];
var array_typ = [];
var array_dla = [];
var array_wie = [];
var array_cen = [];
var array_licz = [];
var str = jQuery("#all_str").val();
array1 = str.split('#');
var size = array1.length;
var str1 = "Tax A - child";
var str2 = "Tax A - elder";
var str1w = "Number of children";
var str2w = "Number of elders";
var html = "</div>";
var html2 = "";
for (i = 0; i < size; i++) {
array2 = array1[i].split('#');
array_typ[i] = array2[0];
array_dla[i] = array2[1];
array_wie[i] = array2[2];
array_cen[i] = array2[3];
}
for (j = 0; j < size; j++) {
if (array_dla[j] == str1) {
if (jQuery.inArray(str1w, array_licz) == -1) {
array_licz[j] = str1w;
}
}
if (array_dla[j] == str2) {
if (jQuery.inArray(str2w, array_licz) == -1) {
array_licz[j] = str2w;
}
}
}
var size2 = array_licz.length;
for (k = 0; k < size2; k++) {
html += ' <label for="field[' + k + ']">' + array_licz[k] + ' ages ' + array_wie[k] + ' </label> ';
}
for (l = 0; l < size2; l++) {
html2 += '<input type="text" id="field' + l + '" value=""></input> ';
}
html += '</br>';
html += html2;
html += '</div>';
jQuery("#addon").append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addon"></div>
<input type="hidden" id="all_str" value="XYZ#Tax A - elder#65-99#1#XYZ#Tax A - child#5-18#2#">
Please help
You have invalid tags. Input is a void element and does not needs a closing </input> tag.
<br>, <br/> are valid. </br> is not.
You have one useless for(l=0; l<size2; l++){
Use only the first k one.
Than in CSS set your label to display: block;
jQuery(function( $ ) {
var array1 = [];
var array2 = [];
var array_typ = [];
var array_dla = [];
var array_wie = [];
var array_cen = [];
var array_licz = [];
var str = $("#all_str").val();
array1 = str.split('#');
var size = array1.length;
var str1 = "Tax A - child";
var str2 = "Tax A - elder";
var str1w = "Number of children";
var str2w = "Number of elders";
var html = ""; // </div> ?? You mean Start of a <div>. BTW you have <label> already so ""
// html2 why??
for (i = 0; i < size; i++) {
array2 = array1[i].split('#');
array_typ[i] = array2[0];
array_dla[i] = array2[1];
array_wie[i] = array2[2];
array_cen[i] = array2[3];
}
for (j = 0; j < size; j++) {
if (array_dla[j] == str1) {
if ($.inArray(str1w, array_licz) == -1) {
array_licz[j] = str1w;
}
}
if (array_dla[j] == str2) {
if ($.inArray(str2w, array_licz) == -1) {
array_licz[j] = str2w;
}
}
}
var size2 = array_licz.length;
// Why loop twice size2. Loop once
for (k = 0; k < size2; k++) {
html += '<label for="field[' + k + ']">' +
array_licz[k] + '<br>ages ' + array_wie[k] +
'<br><input type="text" id="field' + k + '" value="">'+
' </label>';
}
$("#addon").append(html);
});
label{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addon"></div>
<input type="hidden" id="all_str" value="XYZ#Tax A - elder#65-99#1#XYZ#Tax A - child#5-18#2#">
The other part of your code can be also improved, but I have no idea what you're after with all those arrays...
$(document).ready(function() {
var array1 = [];
var array2 = [];
var array_typ = [];
var array_dla = [];
var array_wie = [];
var array_cen = [];
var array_licz = [];
var str = $("#all_str").val();
array1 = str.split('#');
var size = array1.length;
var str1 = "Tax A - child";
var str2 = "Tax A - elder";
var str1w = "Number of children";
var str2w = "Number of elders";
var html = "</div>";
var html2 = [];
var html3 = [];
for(i=0; i<size; i++){
array2= array1[i].split('#');
array_typ[i] = array2[0];
array_dla[i] = array2[1];
array_wie[i] = array2[2];
array_cen[i] = array2[3];
}
for(j=0; j<size; j++){
if(array_dla[j]==str1){
if($.inArray(str1w, array_licz) == -1){
array_licz[j]=str1w;
}
}
if(array_dla[j]==str2){
if($.inArray(str2w, array_licz) == -1){
array_licz[j]=str2w;
}
}
}
var size2 = array_licz.length;
for(k=0; k<size2; k++){
html3[k]='<label for="field['+ k +']">'+array_licz[k]+' ages <br>' +array_wie[k] +' </label> <br>';
}
for(l=0; l<size2; l++){
html2[l]='<input type="text" id="field'+l+'" value=""</input> <br></br>';
}
for(var j=0;j<size2;j++){
html += html3[j]+html2[j];
}
//html+='</br>';
//html+=html2;
html+='</div>';
$("#addon").append(html);
});
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addon">
</div>
<input type="hidden" id="all_str" value="XYZ#Tax A - elder#65-99#1#XYZ#Tax A - child#5-18#2#">
Your problem was the way you put the strings together. An easy solution is to use arrays and in the end you can manipulate them more easily

Javascript random table td -- nooverlap vertical-horizontal

I'm trying to avoid horizontal and vertical lines.
It stopped working with the Javascript array and for the rest of it.
I don't know how to create Javascript to randomly generate the first line and don't overlap with daeumjul. Please let me know. The code has been raised to jsfiddle.
Screenshot:
Javascript
var arr_person = ["#B22222","#0000cd","#FF00FF","#DAA520","#008000","#FF69B4","#4B0082","#E6E6FA","#ADD8E6","#90EE90"];
var arr_date = ['mon', 'tue', 'wed', 'thu','fri'];
var arr_subject = ['subject1','subject2','subject3','subject4','subject5'];
var arr_subject_check = new Array();
for(m=0; m < arr_subject.length; m++){
arr_subject_check[m] = new Array();
}
var arr_time = ['morning','after'];
var str = "";
function pickFromPool() {
var r = Math.floor(Math.random() * arr_pool.length);
return arr_pool.splice(r,1)[0];
}
str += "<table>";
for(var i=0; i < arr_date.length; i++){ // arr_date
var arr_pool = arr_person.slice();
str += "<tr>";
for(var j=0; j < arr_subject.length; j++ ){ //arr_subject
var arr_subject_check_cur = arr_subject_check[j].slice();
for(var n=0; n < arr_subject_check_cur.length; n++) {
var dup_index = arr_pool.indexOf(arr_subject_check_cur[n]);
if(dup_index < 0) {
} else {
arr_pool.splice(dup_index,1);
}
}
for(var k=0; k < arr_time.length; k++ ){
var pickedValue = pickFromPool();
arr_subject_check[j].push(pickedValue);
if(k == 0){
str += "<td style='border-left:#fff 4px solid;background-color:" + pickedValue + "'></td>";
} else {
str += "<td style='background-color:" + pickedValue + "'></td>";
}
}
for(var m=0; m < arr_subject_check_cur.length; m++) {
if(arr_subject_check_cur[m] !== '') {
arr_pool.push(arr_subject_check_cur[m]);
}
}
}
str += "</tr>";
}
str += "</table>";
jQuery('body').html(str);
https://jsfiddle.net/ipadorusa/vx8t25ts/1/
I'm trying to avoid horizontal and vertical lines.

Simple Quiz Game JavaScript

I'm just learning now. Can you please help me, why am I not getting the correct output. This is my code:
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
var oList = "<ol>";
//function to print the result in ordered list
function printResult(result){
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[i] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML = message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
I have watched this code over and over again and I still can't understand why am I getting undefined as a result. In the debugger, after the loop I check my vars and everything seems ok.
In your printResult function you are using var i instead of j,
Also you better use innerHtml+=message;
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
//function to print the result in ordered list
function printResult(result){
//HERE:
var oList = "<ol>";
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
<div id="output">
</div>
Basically you have three problems.
reuse of oList, the variable should be inside declared and used only in printResult.
Inside of printResult, use of i where j have been used and
At print, you replace the actual content with new content.
Just a small hint with variable names for counting. It is good practise to start always with i instead of j and go on with the letters in the alphabet.
var quiz = [["When is Bulgaria established?", 681], ["What year was it before 16 years?", 2000], ["When does WWII ends?", 1945]],
answer = [],
correct = [],
wrong = [],
correctAns = 0,
wrongAns = 0;
//function to print the result in ordered list
function printResult(result) {
var oList = "<ol>"; // !!! move variable inside of the function
for (var j = 0; j < result.length; j++) {
oList += "<li>" + result[j] + "</li>"; // !!! use j indstead if i
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message; // !!! append message
}
//looping, adding correct and wrong answeres
for (var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if (parseInt(answer[i]) == quiz[i][1]) {
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if (correct.length < 1 || correct == undefined) {
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1) {
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if (wrongAns > 0) {
print(printResult(wrong));
}
}
Your main mistake is using i intead of j:
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";// here was i before
}

How do i display the longest array in JS?

I want to create a Javascript array of words, then use Javascript to find the longest word and print it to the screen. Here is my code:
var StrValues = []
StrValues[0] = ["cricket"]
StrValues[1] = ["basketball"]
StrValues[2] = ["hockey"]
StrValues[3] = ["swimming"]
StrValues[4] = ["soccer"]
StrValues[5] = ["tennis"]
document.writeln(StrValues);
You can use length to find the longest string in a array. Here is a fiddle http://jsfiddle.net/2sebnb33/1/
for(var i=0;i<StrValues .length;i++){
if(StrValues [i].length>len){
len=StrValues [i].length;index=i;}
}
var strValues = ["cricket", "basketball", "hockey"];
var max = '';
for(var i = 0; i< strValues.length; i++) {
max = strValues[i].length > max.length ? strValues[i] : max;
}
alert(max);
Firstly, you need to correct the way you are creating array.
For instance, it should be like this
var StrValues = [];
StrValues[0] = ["cricket"];
The logic
var longestWord = "";
for (var i = 0 ; i < StrValues.length; i++) {
if(StrValues[i].length > longestWord.length) {
longestWord = StrValues[i];
}
}
See the code below:
var array = [];
array.push("cat");
array.push("children");
array.push("house");
array.push("table");
array.push("amazing");
var maxSize = 0;
var maxSizeWord = "";
for(var i = 0; i < array.length; i++) {
if (maxSize < array[i].length) {
maxSize = array[i].length;
maxSizeWord = array[i];
}
}
alert("The biggest word is '" + maxSizeWord + "' with length '" + maxSize + "'!");

Categories