Javascript Objects / Arrays - How?

This is my first post, and I'm pretty new to javascript, but I was hoping to get some help in creating objects and arrays using javascript.

Basically, I am a way to create an object that will store the following information, i.e.:

[index, name], for example [0, "NameA"] [1, "NameB"], etc.

Not sure how to create an object / array to store this type of information using jQuery.

Secondly, I then need to pass this object / array as a parameter to another function, and then skip this object / array and print its contents.

Again, you do not know how to do this.

It would be very helpful to help above with examples / websites with examples, etc.

Thanks. TT.

+3
source share
4 answers

If you are interested in storing some data in an array and wresting it along with your index, why not do it in the easiest way?

var arr = ["Alpha", "Bravo", "Charlie", "Dog", "Easy"];

for (i = 0; i<5; i++) {
    alert("Element with index " + i + " is " + arr[i] + ".");
}
+10
source

You can find the following interesting article.

In essence, the object (jQuery) returned by the jQuery function $()has a bunch of properties that include one for each element that matches the selector, with the property name being a numeric "index"

For example, given the following HTML

  <p>Hello, World!</p>
  <p>I'm feeling fine today</p>
  <p>How are you?</p>

and selector

$('p');

the returned object will look like this

({length:3, 0:{}, 1:{}, 2:{}})

Using the command .get(), you can access the corresponding elements and work with them accordingly. Following the lead

$(function () {
var p = $('p').get();
for (var prop in p)
  alert(prop + ' ' + p[prop].innerHTML);
});

, , ,

$(function () {
var p = $('p');
for (var i=0; i< p.length; i++)
  alert(i + ' ' + p[i].innerHTML);
});

0 Hello, World!
1 I'm feeling fine today
2 How are you?

, , , , jQuery.

, , ,

  • , Tomas Lycken. , -, ,

    var mySimpleArray = ['a','b','c'];

  • , "" "". , "" , ,

    var myObjectArray = [{ index: 5, name: 'a' },{ index: 22, name: 'b'},{ index: 55, name: 'c'}];

+4

$.each :

http://docs.jquery.com/Utilities/jQuery.each

:

var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };

jQuery.each(arr, function() {
  $("#" + this).text("My id is " + this + ".");
  return (this != "four"); // will stop running to skip "five"
});

jQuery.each(obj, function(i, val) {
  $("#" + i).append(document.createTextNode(" - " + val));
});
+1
//class
function Foo(index, name) {
this.index = index;
this.name = name;}
//object of that class
var obj = new Foo(0, "NameA");

var myArray = new Array();
//add object to array
myArray.push(obj);    

function loopArray(someArray) {
var index; 
var name;
for (var i = 0; i < someArray.length; i++) 
 {
    index = someArray[i].index;
    name = someArray[i].name;
 }
}
+1

Source: https://habr.com/ru/post/1708940/


All Articles