I'm calling the .string method on a string and setting that equal to another variable. It returns an array with the [match value, index, and input].
When I try to refer to the second element in the array, it comes back as undefined. Can someone tell me why that is? Heres my code:
var str = "hello world"
var matchArray = str.match("ell");
=>matchArray = ["ell",index:1,input:"hello world"]
var index = matchArray[1];
console.log(index);
=>undefined
Thanks in advance.
var str = "hello world"
var matchArray = str.match("ell");
matchArray is an Array but in javascript as we know we can set properties in array as well as it's an object.
In the above case, matchArray has only the mathces in the array. but the other properties such as index and input are in the object.
If you do console.dir(matchArray) you would get the properties as well.
So to access those properties use object's notation like matchArray.index or matchArray.input
JavaScript is an interesting language. Although the matchArray object is indeed an array, in JS you can add new members to any object. So, matchArray is an array of length 1, but it also has the members index and input defined on it. Try this:
...
console.log(matchArray.index);
console.log(matchArray.input);
We could define a similar object from scratch like this:
var hybridObj = [ "ell" ]; // It's an array
hybridObj.index = 1; // With props
hybridObj.input = "hello world";
Related
In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length
I am writing a function called "countWords".
Given a string, "countWords" returns an object where each key is a word in the given string, with its value being how many times that word appeared in th given string.
Notes:
* If given an empty string, it should return an empty object.
function countWords(str) {
var obj = {};
var split = str.split(" ");
return split;
}
var output = countWords('ask a bunch get a bunch');
console.log(output); // --> MUST RETURN {ask: 1, a: 2, bunch: 2, get: 1}
Have any idea?
I wont give you finished code ( thats not the sense of a homework) , but i try to get you to solve the problem on your own.
So far you've already got an array of words.
Next lets declare an object we can assign the properties later.
Then we'll iterate over our array and if the array element doesnt exist in our object as key yet ( if(!obj[array[i]])) well create a new property, with elements name and the value 1.( obj[array[i]=1; )
If the element is a key of that object, lets increase its value.
( obj[array[i]]++;)
Then return the object.
So you could use a javascript Map for this like so:
var myMap = new Map();
myMap.set(keyString, count);
and access the value of the key like so:
myMap.get(keyString);
For more information you can read up here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
I have a json string
["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]
I need to get at the data only and I want to extract the string to get the following :
https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
I have tried to use JSON.parse but this does not seem to work
Any help woul dbe appreciated
[] represents an array on JSON. {} represents an Object.
So in order to fetch the first element from you json string, you have to parse the string as a JSON element ;
var arr = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]');
OR when you HAVE a json array already;
var arr = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
Then, go on and fetch the first value from your array which has index 0 as in all programming languages.
var url = arr[0];
It's seems to be a normal array not a JSON, but if you want you can treat it as JSON:
var image = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]')[0];
console.log(image); //https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
Be aware of the difference between an array, and a JSON object.
I have given some examples of the differences and how to access them.
// This is an array containing 1 value.
myobj = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
// it can be accessed by either the array name (since it only hase one value) or the array name and index of the value in cases where the array actually has more than one value.
var example1 = [myobj];
document.write("This is my single value array:<br>" + example1 + "<br><br>");
// This is probably best practice regardless of the number of items in the array.
var example2 = myobj[0];
document.write("Now im specificing the index, incase there are more that one urls in the array:<br>" + example1 + "<br><br>");
// This is a JSON object
myJsonObj = {"url":"https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"}
// You access the value of the URL like this:
var example3 = myJsonObj.url;
document.write("Here is the value from a JSON object:<br>" + example3 );
Hope this helps
Just use parse function:
var text = '["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]';
var obj = JSON.parse(text);
https://jsfiddle.net/esouc488/1/
Can anyone explain how the result of RegExp.prototype.exec is made?
If you try something like that: /d/g.exec("d is a character, dd") the result is an array structured as explained here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
My question is, how the array has non-indexeed properties like index and input?
Normally an array is a collection indexeed by integers ([0...n]);
var re = /d/g;
var str = "domains are always domains";
var result = re.exec(str);
console.log("typeof result", typeof result);
console.log("Array.isArray(result)", Array.isArray(result));
console.log("result.length", result.length);
console.log("result", result);
An array is just an object. In fact, you can make simple array-like objects just like that:
var fakeArr = {}
fakeArr[0] = 'foo';
fakeArr[1] = 'bar';
fakeArr.length = 2;
The only thing that distinguishes an array from a plain object is the behaviour of the .length property and the various array-specific methods on Array.prototype.
I am using an array as defined below
cat_id = Object { 2="text", 3="TKL1", -1="Select an Attribute"}.
when i am trying to retrieve the length of "cat_id" as
var l = cat_id.length;
its showing the length as "undefined".
But, I am unable to get the length of "cat_id". I am unable to use replace(), indexOf() and split() functions.
for example:
var index = cat_attr.indexOf(",")
Its showing error as below:
TypeError: cat_attr.indexOf is not a function
This isn't array, this is Object. Array defined in this way: [1,2,3]. If you want retrieve the "length" of object you can do this in this way:
var students = {job:92, adam:67,sara:83};
var studentNames = Object.keys(students);
var studentsLength = studentNames.length;
If you want split object to array you can do this in this way:
var students = {jon:92, adam:67,sara:83};
var studentNames = Object.keys(students);
var studentArray = studentNames.map(function(name){
var student = {};
student.name = name;
student.grade = students[name];
return (student);
}); // [{name:jon,grade:92},{name:adam,grade:67},{name:sara,grade:83}]
cat_id variable you defined as not an array, it is a javascript object. That is why it is not behaving like array! [] is the array notation. Use array notation [] instead of {} object notation you have used.
Your problem is wrong type and wrong syntax.
In your question your cat_id is an Object, not string or array. So you can not call length() or indexOf() funtion.
Moreover, you typed wrong syntax, it should be:
var cat_id = { 2: 'text', 3: 'TKL1', -1: 'Select an Attribute'}.
Here is how to retrieve property count (size and/or length)
size_obj = Object.keys(my_object).length;
As in
size_cat_id = Object.keys(cat_id).length;