Show elements from array in jquery - javascript

I'm new in web development. I converted the list of image names to an array by following codeL
var image_array = $("#image-ul img").map(function() {return $(this).attr("src");});
Now I want to show some of these images. I show all the images by adding following codeL
$('#image-ul img').css('display','block');
But I want some of the images, like the following:
for (var i=0; i<2; i++) { $('#image-ul img:image_array[i]').css('display','block');}
How can I do this?

You don't really use a for loop to do that, you select the images and limit the selection with eq(), lt(), gt() etc. So for anyting with an index lower than 2, you do :
$('#image-ul img:lt(2)').show();

Try
for (var i=0; i<2; i++) { $('#image-ul img:eq(' + i +')').css('display','block');}
Or
for (var i=0; i<2; i++) { $('#image-ul img').eq(i).css('display','block');}

Change this line
for (var i=0; i<2; i++) { $('#image-ul img:image_array[i]').css('display','block');}
to this
for (var i=0; i<2; i++) { $('#image-ul img').eq(i).show(); }
as Juhana pointed out .show() is the best way to show display an element with jQuery

Related

Uncaught TypeError: Cannot set property '203' of undefined

var wins = [] ;
for(var i=0; i<11; i++){
wins[i] = [] ;
for(var j=0;j<11; j++){
wins[i][j] = [] ;}}
var count = [] ;
for(var i=0; i<11; i++){
for(var j=0; j<7; j++){
for(var k=0; k<5; k++){
wins[i][j+k][count] = true;
}
count++ ;
}}
for(var i=0; i<11; i++){
for(var j=0; j<7; j++){
for(var k=0; k<5; k++){
wins[j+k][i][count] = true;
}
count++ ;
}}
for(var i=0; i<7; i++){
for(var j=0; j<7; j++){
for(var k=0; k<5; k++){
wins[i+k][j+k][count] = true;
}
count++ ;
}
}
for(var i=0; i<7; i++){
for(var j=14; j>3; j--){
for(var k=0; k<5; k++){
wins[i+k][j-k][count] = true;
}
count++ ;
} }
i get the error Uncaught TypeError: Cannot set property '203' of undefined.
how can i fix it?
i get error in last for loop.
i'm newbie in java script.
Preliminary note :
What you want to achieve is not clear, and in my opinion you shouldn't need all these arrays. The better solution would be to redesign your code entirely, but in order to help you with that part, you would need to explain what is the actual goal and problem you are trying to solve with your code.
However, in the following answer I'll try to give you guidance on how you can debug and understand your own code, which I hope will help you anticipate and think more clearly about your code before you write it.
As general guideline in this kind of problems, where you are manipulating a lot of arrays :
What is likely to happen is that you forgot to define a value in one of your arrays, or you are trying to access an index larger than the array.
e.g:
let arr = []
arr[0] = 10;
arr[2] = 42;
console.log(`Length of array is : ${arr.length}`);
for (let i in [0,1,2,3]) {
console.log(arr[i]);
}
So, you could debug your code by
print the arrays in console to check where you might have forgotten to define a value
Check that the indices you use are not larger that the size of your arrays.
For your particular code :
triple for loops don't help to see clearly what happens.
It's a bit difficult to propose something else since you didn't explain the goal of your program, but in general I would try to not having so many complicated loops with calculations in the indices.
Having a loop with j decreasing from 14 to 4, in between two other loops with k and i, with things like [j-k] as index is likely to cause trouble, even to the most experienced JavaScript coders.
To debug your program, I would recommend you to print the indices in the console to understand what happens :
Example for the last part of your code (but you should do the same with the other parts)
for(var i = 0; i < 7; i++) {
for(var j = 14; j > 3; j--) {
for(var k = 0; k < 5; k++) {
console.log(`wins[${i+k}][${j-k}]`);
}
}
}
Check that these are really the one you wanted to access, and that you correctly defined them previously.

How do i split up an array that holds an array?

Hello my fellow JS friends,
I am letting a user import a csv file (excel sheet) and i convert that into
an array. which has 472 rows and 87 columns in this case.
so my array looks like this:
and everything is separated by commas like a usual array.
The issue is I need to separate the array within the array and when i do that i get an array with the length of 9 million, which i think is wrong
vm.allTextLines = files.split(/\r\n|\n/);
var headers = vm.allTextLines[0].split(',');
vm.columnCount = headers.length;
vm.rowCount = vm.allTextLines.length - 1;
for (var i = 0; i < vm.allTextLines.length; i++) {
// split content based on comma
var data = vm.allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
vm.lines.push(tarr);
}
}
//this is where i split the array that contains the csv
//data and put it into its own array I believe this is
//where the issue is.
for(var i=1;i<vm.allTextLines.length; i++){
vm.uniqueAll.push(vm.allTextLines[i].split(','));
for(var j=0; j < vm.uniqueAll.length; j++){
for(var r =0; r < vm.uniqueAll[j].length; r++){
vm.arrayOfValuesOfFile.push(vm.uniqueAll[j][r]);
}
}
}
If you can help me correct this for each I would appreciate it alot.
Thank you in advance guys!
I agree with you about the place of error, because it seems you nested the loop in a wrong way. Following a snippet where you can check what I mean.
i.e:
let vm = {
allTextLines:['h1,h2,h3','row1val1,row1val2,row1val3', 'row2val1,row2val2,row2val3'],
uniqueAll: [],
arrayOfValuesOfFile:[]
}
// Here you should not nest the loop
for(var i=1;i<vm.allTextLines.length; i++){
vm.uniqueAll.push(vm.allTextLines[i].split(','));
}
for(var j=0; j < vm.uniqueAll.length; j++){
for(var r =0; r < vm.uniqueAll[j].length; r++){
vm.arrayOfValuesOfFile.push(vm.uniqueAll[j][r]);
}
}
console.log('allTextLines', vm.allTextLines);
console.log('uniqueAll', vm.uniqueAll);
console.log('arrayOfValuesOfFile', vm.arrayOfValuesOfFile);
Of Course you could easily optimize the algorithm:
let vm = {
allTextLines:['h1,h2,h3','row1val1,row1val2,row1val3', 'row2val1,row2val2,row2val3'],
uniqueAll: [],
arrayOfValuesOfFile:[]
}
for(var i=1;i<vm.allTextLines.length; i++){
let currentLinesValue = vm.allTextLines[i].split(',');
vm.uniqueAll.push(currentLinesValue);
for(var r =0; r < currentLinesValue.length; r++){
vm.arrayOfValuesOfFile.push(currentLinesValue[r]);
}
}
console.log('allTextLines', vm.allTextLines);
console.log('uniqueAll', vm.uniqueAll);
console.log('arrayOfValuesOfFile', vm.arrayOfValuesOfFile);
First you should transform you bidimensional array into a one-dimension array.
var allTogether = []; // Array with all your CSV (no matter from which file it came from)
for (var i = 0; vm.allTextLines.length; i++) {
allTogether.push(vm.allTextLines[i]); // Gets the CSV line an adds to a one-dimension array
}
// Now you can iterate over the one-dimension array
for (var i = 0; allTogether.length; i++) {
var csvFields = allTogether[i].split(',');
// Here goes your code that works with the CSV fields.
}

how to write a XML data 2 Dimensional Array

the snippt shows the XML detail : please referes to the image, shows the table...
<ExtractSummaryDateSet>
<_date>2017-09-20</_date>
<_portfolioSummaries>
<ExtractSummaryDateSetDetail>
<_portfolioName>52613661_CL</_portfolioName>
<_detail>
<Before>0</Before>
<After>-329</After>
<ChangeMaturing>0</ChangeMaturing>
<ChangeNew>-329</ChangeNew>
</_detail>
</ExtractSummaryDateSetDetail>
<ExtractSummaryDateSetDetail>
<_portfolioName>52613661_LP</_portfolioName>
<_detail>
<Before>0</Before>
<After>-329</After>
<ChangeMaturing>0</ChangeMaturing>
<ChangeNew>-329</ChangeNew>
</_detail>
</ExtractSummaryDateSetDetail>
<ExtractSummaryDateSetDetail>
<_portfolioName>526136|Total</_portfolioName>
<_detail>
<Before>0</Before>
<After>-329</After>
<ChangeMaturing>0</ChangeMaturing>
<ChangeNew>-329</ChangeNew>
</_detail>
</ExtractSummaryDateSetDetail>
I am trying to use 2 Dimential arrays in XML to create a table HTML
for (var i = 0; i < x.length; i++){
var row= x[i];
var date = row.getElementsByTagName("Date")[0].childNodes[0].nodeValue;
for(var j = 0;j < row.length; j++){
var before = row[j].getElementsByTagName("Before")[0].childNodes[0].nodeValue;
var after = row[j].getElementsByTagName("after")[0].childNodes[0].nodeValue;
}
}
just wanna know is the example above semantically correct?
in the second array can i use row[j] to call the array
for (var y = 0; y < x.length; y++){
for (var i = 0; i < x[i].length; i++){
table_summary +="<th></th><th></th><td>" + x[y][j].getElementsByTagName("_date")[0].childNodes[0].nodeValue + "</td>" ;
}
how do I pass the value correctly? x[y][i] can't not find the value.
I am working on XML format in web application and encounter to similar your issue. You can transform XML to HTML like your method but create HTML tags from XML is very cumbersome.
I suggest you use XSLT for this transform.
I created a simple XSLT for your XML and converted this transform very easily.
Please see Online transform and click html in result panel to see HTML output for your XML.
You can consider a multi dimensional array as an array of arrays.
so this is fine :
for (var i = 0; i < x.length; i++){
var row= x[i]
for(var j = 0;j < row.length; j++){
var before = row[j];
}
}
However you can also write this as :
for (var i = 0; i < x.length; i++) {
for(var j = 0;j < x[i].length; j++) {
var before = x[i][j];
}
}

Replace a default link with another link

I want change the link attribute href of an existing link with another link using JavaScript. How can I do this?
Here is the link:
See moreSee moreSee more
I have tried the following but it doesn't work:
var links = document.getElementsByTagName('a');
var len = links.replace;
for(var i=0; i<replace; i++){
links[i].href = "newlink.php?+BLABLABAL";
}
Replace links.replace by links.length, since you are iterating over the links array.
Working code:
// This is an array of links
var links = document.getElementsByTagName('a');
// The length of the array
var len = links.length;
// Iterate over the array
for(var i = 0; i < len; i++){
links[i].href = "https://twitter.com";
}
Working demo: http://codepen.io/anon/pen/yYBdgQ
Change your js code with this :
var links = document.getElementsByTagName('a');
var len = links.length;
for(var i=0; i<len; i++){
links[i].href = "newlink.php?+BLABLABAL";
}
You have to take the length of links in var len, and then run the loop through len

Referencing Javascript array element via loop variable

I've come across writing a piece of code where I wanted to reference the 2D array d2_arr[][] in a loop like so.
for (var i=0; i<d2_arr[i].length; i++) {
//do something
}
Google Script compiler throws an error "cannot read length property from undefined". When I changed [i] for [1], it worked just fine. Could anyone please explain why this is wrong? And a related question: Can a 2D array have a different number of elements in a row? theoretically. An example would be:
[[1,2],[3,4,5],[6,7,8,9],[10,11]]
EDIT. Full code part.
var ids = [];
var j = 0;
for (var i=0; i<d2_arr[i].length; i++){
if (d2_arr[i][2]<=0.05){
ids[j]=d2_arr[i][0];
j++;
}
}
I understood the mistake. Thank you!
You typically need a nested for loop to traverse a 2-D array
var d2_arr = [[1,2],[3,4,5],[6,7,8,9],[10,11]]
for (var i=0; i<d2_arr.length; i++){
for (var j=0; j<d2_arr[i].length; j++){
console.log(d2_arr[i][j] + ' ')
}
}
It is perfectly fine for arrays to be "jagged" and contain uneven sized arrays in the main array.
Here is a fiddle http://jsfiddle.net/7Lr4542s/
Arrays in JS can be of any size and any type. You can combine number and strings in array.
var twoDArray = [[1], ["one", "two"], ["i", "ii", "iii"]];
for(var i = 0; i < twoDArray.length; i++) {
for(var j = 0; j < twoDArray[i].length; j++) {
print(twoDArray[i][j]);
}
}
var threeDArray = [[["1.1.1", "1.1.2"], ["1.2.1", "1.2.2"]], [["1.2.1", "1.2.2"], ["1.2.1", "1.2.2"]], [["2.1.1", "2.1.2"], ["2.2.1", "2.2.2"]], [["2.2.1", "2.2.2"], ["2.2.1", "2.2.2"]]];
for(var i = 0; i < threeDArray.length; i++) {
for(var j = 0; j < threeDArray[i].length; j++) {
for(var k = 0; k < threeDArray[i][j].length; k++) {
print(twoDArray[i][j][k]);
}
}
}

Categories

Resources