how do i get the end key value for a javascript array?
i want to compare it with another value.
EDIT: and how do you declare a value directly with a declaration of an array. i have to use 2 lines for it.
var arrayname = new Array();
arrayname[] = 'value';
could one do that in one line?
You can create arrays in one of many ways.
var foo = new Array();
foo[0] = 'a';
foo[1] = 'b';
foo[2] = 'c';
//is the same as:
var foo = new Array();
foo.push('a');
foo.push('b');
foo.push('c');
//is the same as:
var foo = [];
foo.push('a');
foo[1] = 'b';
foo[foo.length] = 'c';
//is the same as:
var foo = ['a','b','c'];
//is the same as:
var foo = 'a|b|c'.split('|');
Of course, if you only want to build an array to pass the array to another function, you can build it anonymously on the fly:
doSomething('param1', ['a','b','c'], 'param3');
You can initialize an array at one go using:
var arrayname = [ 'value' ];
Accessing the last value uses:
arrayname[arrayname.length-1];
The previous assumes that the array has a length greater than zero. If the array can be empty you should check that length is greater than zero before trying to access the last element.
Related
I have varaible which hold value like this var item_size=74X80(space here)30 i.e in browser it looks like "74x80 30" I want to divide it place in separate varaible
i. var a=74X80;
ii. var b=30;
so after slicing with space it should assign values into separate variable using javascript
<script>
var item_size = item_size.split(" ");
alert(item_size[1]);
alert(item_size[2]);
</script>
var item_size = "74X80 30";
item_size = item_size.split(" ");
alert(item_size[0]);
alert(item_size[1]);
console.log(a);
console.log(b);
You can use ES6 array destructuring assignment:
var [a,b] = '74X80 30'.split(' ')
console.log(a)
console.log(b)
Arrays are zero indexed - so you need
var item_size="74X80 30";
var item_size_portions = item_size.split(" ");
var a = item_size_portions[0];
var b = item_size_portions[1];
console.log(a); // gives 74X80;
console.log(b); // gives 30;
Accessing array elements
JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's length property minus 1. Using an invalid index number returns undefined.
You have to use 0 to access the first element, 1 to access the second element an so on....:
var item_size = "74X80 30";
item_size = item_size.split(" ");
alert(item_size[0]);
alert(item_size[1]);
I have array named a which contain number of words with certain characters . I want to classify it by it's name by removing # symbol. I think peoples may be unclear by my question so I have gave output of this program below.
My Array:-
var a = ['#name1#','#name2#','#name3#','#name1#','#name2#'];
function classify(a){
var t = {};
var y = [];
a.forEach(function(f){
var txt = f.replace('#','').trim();
var txtnode = document.createTextNode(f);
y.push(txtnode);
t[txt] = y;
})
return t;
}
console.log(classify(a))
Output of this program that I want to obtain : -
{
name1:(2) [text, text]
name2:(2) [text, text]
name3:(1) [text]
}
More information about given output :-
The given output may not be accurate because it is copied from console but this may give hints for programmer to solve this problem name1 property of object contain 2 array which contain two textnodes having same type of data from same array they are #name1# in first textnode and #name1# in another textnode of property name likewise same in name2 property of object contains #name2# in both textnodes in array similarly name3 property of object contain only 1 textnode with data #name3
inside textnodes :-
{
name1:[#name1#,#name1#],
name2:[#name2#,#name2#],
name3:[#name3#]
}
Please Don't use jquery
Your problem is that you are adding everything to a single array instead of creating a different array for each entry in the object.
Another problem with your code is that f.replace('#', '') only replaces the first instance of # in f.
This should have the desired behavior:
function classify(a){
var t = {};
a.forEach(function(f){
var txt = f.replace(/#/g,'').trim();
var txtnode = document.createTextNode(f);
t[txt] = (t[txt] || []).concat(txtnode);
})
return t;
}
var a = ['#name1#','#name2#','#name3#','#name1#','#name2#'];
var classified = classify(a);
console.log(classified.name1.length);
console.log(classified.name2.length);
console.log(classified.name3.length);
You can use Array#reduce to create an object from the array. On each iteration, get the key by removing the # signs.
If the key doesn't exist on the object, add it as a property with an empty array as value.
Push the current item to the relevant array.
var a = ['#name1#','#name2#','#name3#','#name1#','#name2#'];
var result = a.reduce(function(r, s) {
var key = s.replace(/#/g, '');
r[key] || (r[key] = []);
r[key].push(s); // document.createTextNode(s) instead of s in your actual code
return r;
}, {});
console.log(result);
I understand that there are no associative arrays in JavaScript, only objects.
However I can create an array with string keys using bracket notation like this:
var myArray = [];
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray); // Prints [a: 200, b: 300]
So I want to do the exact same thing without using bracket notation:
var myNewArray = [a: 200, b: 300]; // I am getting error - Unexpected token:
This does not work either:
var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?
JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).
So look at your code first:
var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300
It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!
So to start with what you want:
You can't create a JavaScript array and pass no number attributes to it in one statement.
But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.
You can use Map:
var arr = new Map([
['key1', 'User'],
['key2', 'Guest'],
['key3', 'Admin'],
]);
var res = arr.get('key2');
console.log(res); // The value is 'Guest'
You want to use an object in this case
var myObject = {'a' : 200, 'b' : 300 };
This answer links to a more in-depth explanation: How to do associative array/hashing in JavaScript
Well, you are creating an array, which is in fact an object:
var arr = [];
arr.map;
// function(..)
arr['map'];
// function(..)
arr['a'] = 5;
console.log(arr instanceof Object); // true
You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).
You can refer to an object fields with the [] syntax.
I achieved this by using objects. Your create an object, and loop through using for in loop. each x will be the index and holder[x] will be the value. an example is below.
var test = {'hello':'world','hello2':'world2'}
for(let x in holder)
{
let inxed = x;
let value = holder[x]
console.log('index ' + x + ' has value of ' + value)
}
Associate array is an array indexed with name similar to an object instead of numbers like in regular array. You can create an associative array in the following way:
var arr = new Array(); // OR var arr = [];
arr['name'] = 'david'
arr['age'] = 23;
console.log(arr['name']);
You can do what you wanted to do this way:
myNewArray = new Array ({'a' : 200, 'b' : 300})
Let's say I have an array named derps and then I make an array inside it:
derps[0]=new Array();
how do I get/set data in the newly created array derps[0]?
Simply do this:
derps[0][0] = 'foo';
derps[0][1] = 'bar';
derps[0].push('foobar');
derps[0] = derps[0].concat([5,6,7]);
// Etc, etc.
console.log(derps[0][1]); // 'bar'
console.log(derps[0][2]); // 'foobar'
console.log(derps[0]); // ["foo", "bar", "foobar", "foobar", 5, 6, 7]
Basically, access derps[0] like you'd access any other array, because it is an array.
I'm not going to list All methods you can use on derps[0] ;-)
Also, instead of:
derps[0] = new Array();
You can use the "array literal" notation:
derps[0] = []; // Empty array, or:
derps[0] = ['foo', 'bar', 'foobar']; // <-- With data.
You can create the array with data already in it:
derps[0] = [1, 2, 3];
You can assign values to the array:
derps[0] = new Array();
derps[0][0] = 1;
derps[0][1] = 2;
derps[0][2] = 3;
You can push values to the array:
derps[0] = new Array();
derps[0].push(1);
derps[0].push(2);
derps[0].push(3);
You can push data into the new array:
derps[0].push("some data");
As an aside: you may also use an array literal to create derps[0]:
derps[0] = [];
Easy:
var derps = [];
derps.push([]);
derps[0].push('foo');
derps[0].push('bar');
If you really wish to instantiate the type of the variable before, you can proceed this way (JSFiddle).
var derps = [];
derps[0] = [];
derps[0][0] = "test";
derps[0][1] = "test2";
document.write(derps[0][1]);
Don't forget to write var if you don't want the variable to be global.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamically creating keys in javascript associative array
usually we initialize an array like this:
var ar = ['Hello', 'World'];
And for access to it's values we do:
alert(ar[0]); // Hello
But I want a custom index to assign, ex:
var ar = ['first' => 'Hello', 'second' => 'World'];
and then
alert(ar['first']);
But I can't find how, is there something like this that I could do for assign?
Thank's!
You could use Object instead of Array, you can specify named properties for object
var ar = {
first: 'hello',
second: 'world'
};
alert(ar['first']);
Also you can just assign properties with string keys to your array, this will also work:
var ar = [];
ar['first'] = 'first';
alert(ar['first']);
You need to use an Object.
var obj = {'first': 'hello', 'second': 'world'};
alert(obj.first);
Objects in JavaScript are just property bags (hashtables).
You can:
var ar = {};
ar["name"] = "Dave";
ar["salary"] = "Millions";
alert(ar.name); //Dave
alert(ar["salary"]); //millions
JavaScript allows you to be pretty flexible in how you create these objects.
JavaScript doesn't have associative arrays as such, but object literals:
var obj = {foo:'bar'};
obj.something = 'else';
//or:
obj['foo'] = 'BAR';
JS won't make a fuss if you create named indexes on an array (because the Array object traces back to the Object prototype) but you'll loose all use of Array features (methods like sort, or the magic length property, to name just a few)
just use
var h = new Object(); // or just {}
h['one'] = 1;
h['two'] = 2;
h['three'] = 3;
// show the values stored
for (var k in h) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
alert('key is: ' + k + ', value is: ' + h[k]);
}
}
You can do this:
var ar = {
'first' :'Hello',
'second' : 'World'
};
As you can see, this is the way you initialize objects in Javascript. Javascript blurs the lines between associative arrays and objects.
You can then access this with:
ar['first']
Or even:
ar.first
Also, you could leave out the quotes in the key initialization, like so:
var ar = {
first :'Hello',
second : 'World'
};