I am using the following JavaScript code:
var a = [23, 34, 45, 33];
Is a considered an array of integers?
Yes, a is an array. However, since Javascript isn't statically typed, it can contain other types as well, such as strings, objects, other arrays and so on. Therefore, tagging it as "an array of integers" wouldn't be right.
JavaScript doesn't have an Integer type. It is an Array containing Numbers (but not limited to containing only Numbers)
You are creating an array a using an array literal.
An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.
As the other answers already pointed out, JavaScript arrays are able to contain elements of different data types.
Yes, it is. It really is.
Interesting question...
a is considered an array of integers as long as you want it that way since javascript is dynamically typed, ie. you could potentially do:
var a = [23, 34, 45, 33];
alert(a[0] + 1); // shows 24
a = "sometext";
alert(a + 1); // shows "sometext1"
HTH.
Javascript supports var so you can have combination of string, int, decimal here.
To check further details see this link http://javascript.blogsome.com/category/1/javascript-array/
Related
I have an array like below
arr=[];
arr[0]={"zero": "apple"};
arr[1]={"one": "orange"};
arr["fancy"]="what?";
but i am getting length as 2 when i do console.log(arr.length) even though i am able to console all the values .
and not able to get all values while doing console.log(JSON.stringify(arr))
What is the issue here.
here is the link to fiddle fiddle
.length is a special property in Javascript arrays, which is defined as "the biggest numeric index in the array plus one" (or 2^32-1, whatever comes first). It's not "the number of elements", as the name might suggest.
When you iterate an array, either directly with for..of or map, or indirectly with e.g. JSON.stringify, JS just loops over all numbers from 0 to length - 1, and, if there's a property under this number, outputs/returns it. It doesn't look into other properties.
The length property don't work as one will expect on arrays that are hashtables or associative arrays. This property only works as one will expect on numeric indexed arrays (and normalized, i.e, without holes). But there exists a way for get the length of an associative array, first you have to get the list of keys from the associative array using Object.keys(arr) and then you can use the length property over this list (that is a normalized indexed array). Like on the next example:
arr=[];
arr[0]={"zero": "apple"};
arr[1]={"one": "orange"};
arr["fancy"]="what?";
console.log(Object.keys(arr).length);
And about this next question:
not able to get all values while doing console.log(JSON.stringify(arr))
Your arr element don't have the correct format to be a JSON. If you want it to be a JSON check the syntax on the next example:
jsonObj = {};
jsonObj[0] = {"zero": "apple"};
jsonObj[1] = {"one": "orange"};
jsonObj["fancy"] = "what?";
console.log(Object.keys(jsonObj).length);
console.log(JSON.stringify(jsonObj));
From MDN description on arrays, here, "Arrays cannot use strings as element indexes (as in an associative array) but must use integers."
In other words, this is not Javascript array syntax
arr["fancy"]="what?";
Which leads to the error in .length.
I'd like some help to clarify how exactly I should be using filter.
The following works just fine:
let nums = [10, 12, 15, 20]
nums.filter(num => num > 14)
result = [15, 20]
If I understand this correctly, I'm passing in a function with num as argument.
Now here's where it all gets confusing (Keep in mind I'm not an advanced js programmer)
I have an array of html elements
let fields = document.getElementsByClassName("f-field")
Every single element in the returned array contains a bunch of other html elements, it looks something like this.
<div class="f-field">
<textarea id="9008" name="Logo"></textarea>
</div>
The inner HTML can be textareas, selects, inputs, whatever...
I tried this and it says
"fields.filter is not a function"
fields.filter(field => field.getElementsByName("Logo"))
I'm assuming that filter does not work for an Array of html elements. Or am I doing this wrong?
Thanks in advance, I'm trying to really understand javascript
DOM query methods like getElementsByClassName and querySelector return collections that are array-like, but not actually arrays (HTMLCollection, NodeList). They have numbered keys you can iterate over, and length properties too, but do not support array generics like filter, forEach or map.
You can cast an array-like object into an array using array = Array.from(source). If you're writing ES6, you could also use the spread operator: array = [...source]
So, you could write your code as follows:
let fields = document.querySelectorAll('.f-field');
logos = Array.from(fields).filter(field => field.getElementsByName('logo'));
Then again, why do all that filtering and traversing when you could just pass a CSS selector straight to querySelectorAll? e.g.
let logos = Array.from(document.querySelectorAll('.f-field [name="logo"]'));
Yup this is a little tricky. getElementsByClassName does NOT return an Array. It returns an HTMLCollection, which behaves like an array in some ways (you can iterate over it and it has a length), but does not contain most of the Array methods.
You can convert to an array as follows
var filteredFields = [...document.getElementsByClassName("f-field")].filter(item => itemTest(item));
Find out more about the spread operator at MDN
I'm trying to convert a js array to string. This string should be a value of a hidden input as so:
<input type="hidden" ng-model="myIndicationsString" />
In the controller:
$scope.myIndicationsString = $scope.productIndications.toString();
The problem is, it changes the array to a string value so when a change is needed to occur in $scope.productIndications it fails to do so.
Is there a method like toString() without changing the actual element? only returning a string result?
Thanks before
Try using JSON.stringify to generate a string representation of your array, like this:
$scope.myIndicationsString = JSON.stringify($scope.productIndications);
This function will not modify the original array, so you'll be able to continue using that as before. If you need to turn that string that stringify returns back into an array, you can use JSON.parse to do so.
I am not sure what you are exactly asking but join might be what you are looking for.
Let say your array is array = [John, Steve, Rob, Mary, Tom], then what you can do is:
array.join(',') \\John,Steve,Rob,Mary,Tom
array.join(' ') \\John Steve Rob Mary Tom
array.join('And') \\JohnAndSteveAndRobAndMaryAndTom
Slightly confused what you are asking, however, assuming you are using angularjs, you can make an identical copy of a scope variable as to maintain the state of the original variable.
var test = [1, 2, 3],
test2;
angular.copy(test, test2);
test2 should now be an identical copy that you can manipulate, without affecting test.
I'm writing a JavaScript interpreter for extremely resource-constrained embedded devices (http://www.espruino.com), and every time I think I have implemented some bit of JavaScript correctly I realise I am wrong.
My question now is about []. How would you implement one of the most basic bits of JavaScript correctly?
I've looked through the JavaScript spec and maybe I haven't found the right bit, but I can't find a useful answer.
I had previously assumed that you effectively had two 'maps' - one for integers, and one for strings. And the array length was the value of the highest integer plus one. However this seems wrong, according to jsconsole on chrome:
var a = [];
a[5] = 42;
a["5"]; // 42
a.length; // 6
but also:
var a = [];
a["5"] = 42;
a[5]; // 42
a.length; // 6
So... great - everything is converted into a string, and the highest valued string that represents an integer is used (plus one) to get the length? Wrong.
var a = [];
a["05"] = 42;
a.length; // 0
"05" is a valid integer - even in Octal. So why does it not affect the length?
Do you have to convert the string to an integer, and then check that when converted back to a string, it matches?
Does anyone have a reference to the exact algorithm used to store and get items in an array or object? It seems like it should be very simple, but it looks like it actually isn't!
As the specs said, and was noted by others:
"A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1."
That's explain why in your scenario "5" is considered an array index and "05" is not:
console.log("5" === String("5" >>> 0));
// true, "5" is equal to "5", so it's an index
console.log("05" === String("05" >>> 0));
// false, "05" is not equal to "5", so it's not an index
Note: the Zero-fill right shift is the shortest way in JS to have a substitute of ToUint32, shifting a number by zero.
See MDN
It's possible to quote the JavaScript array indexes as well (e.g.,
years["2"] instead of years[2]), although it's not necessary. The 2 in
years[2] eventually gets coerced into a string by the JavaScript
engine, anyway, through an implicit toString conversion. It is for
this reason that "2" and "02" would refer to two different slots on
the years object and the following example logs true:
console.log(years["2"] != years["02"]);
So with a["5"] you are accessing the array while a["05"] sets a property on the array object.
Arrays are just objects. That means they can have additional properties which are not considered elements of the array.
If the square bracket argument is an integer, it uses it to perform an assignment to the array. Otherwise, it treats it as a string and stores it as a property on the array object.
Edit based on delnan's comment and DCoder's comment, this is how JavaScript determines if it is an appropriate index for an array (versus just a property):
http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
Arrays are also objects.
By doing this
a["05"] = 5;
You are doing the same thing as:
a.05 = 5;
However, the above will result in a syntax error, as a property specified after a dot cannot start with a number.
So if you do this:
a = [];
a["05"] = 5;
you still have an empty array, but the property of a named 05 has the value 5.
The number x is an array index if and only if ToString(ToUint32(x)) is equal to x (so in case of "05" that requirement is not met).
Why is this extremely basic JavaScript array giving me a length of 13 when there are only 3 key/value pairs in it. It makes sense that it might think 13 as 0 based index and my last array has a key of 12, but I need to have any array that has a key/value pair that returns me the correct number of pairs. The keys need to be numbers.
http://jsfiddle.net/fmgc8/1/
EDIT: this is how I solved it thanks.
http://jsfiddle.net/fmgc8/4/
it's because the highest number you have is:
array['12'] = 'twelve';
This creates an array length of 13 (since it's 0 based). JavaScript will expand the array to allocate the number of spots it needs to satisfy your specified slots. array[0..9] is there, you just haven't placed anything in them.
There is no diffrence between array['12'] and array[12] (array['12'] is not considered as associative array element). To find associative array length
The length property of arrays returns the biggest non-negative numeric key of the object, plus one. That's just the way it's defined.
If you want to count the key-value pairs, you're going to have to count them yourself (either by keeping track of them as they are added and removed, or by iterating through them).
Or, rearrange your array like this:
var array = [];
array.push(['10','ten']);
array.push(['11','eleven']);
array.push(['12','twelfe']);
alert(array.length);