admin管理员组文章数量:1312895
Sorry for misleading title here, I wasn't able to frame any proper one.
I am confused in array when there is nothing inside them (prints by empty × n
) but they have length.
e.g. I create array by const a = [,,,]
. This creates an array whose length is 3 but nothing inside it. If i print it in browser console, it prints the following:
What does empty mean here?
If I run map or forEach function and try to console something, I get nothing.
Have added some code.
const a = [,,,]
console.log("print a: ",a)
console.log("print a.length: ",a.length)
console.log("print typeof a[0]: ", typeof a[0])
console.log("a.forEach((data, index) => { console.log(data, index) }): ", a.forEach((data, index) => { console.log(data, index) }))
console.log("")
const b = [undefined, undefined, undefined]
console.log("print b: ", b)
console.log("print b.length: ", b.length)
console.log("print typeof b[0]: ", typeof b[0])
console.log("b.forEach((data, index) => { console.log(data, index) }): ", b.forEach((data, index) => { console.log(data, index) }))
console.log("")
console.log("pare a[0] and b[0]: ", a[0] === b[0])
Sorry for misleading title here, I wasn't able to frame any proper one.
I am confused in array when there is nothing inside them (prints by empty × n
) but they have length.
e.g. I create array by const a = [,,,]
. This creates an array whose length is 3 but nothing inside it. If i print it in browser console, it prints the following:
What does empty mean here?
If I run map or forEach function and try to console something, I get nothing.
Have added some code.
const a = [,,,]
console.log("print a: ",a)
console.log("print a.length: ",a.length)
console.log("print typeof a[0]: ", typeof a[0])
console.log("a.forEach((data, index) => { console.log(data, index) }): ", a.forEach((data, index) => { console.log(data, index) }))
console.log("")
const b = [undefined, undefined, undefined]
console.log("print b: ", b)
console.log("print b.length: ", b.length)
console.log("print typeof b[0]: ", typeof b[0])
console.log("b.forEach((data, index) => { console.log(data, index) }): ", b.forEach((data, index) => { console.log(data, index) }))
console.log("")
console.log("pare a[0] and b[0]: ", a[0] === b[0])
The only thing which differs is when I print a and b (though stackoverflow console prints them same but browser console prints differently) and when I try to loop through the array. Also momentjs isEqual gives them equal (jsfiddle here)
My main doubts are:
- What type of array is it?
- What does empty mean here?
- How is it different from array which has all undefined values or empty array? or is it not?
- Do we use it or any sample use case for this one
I have read about null and undefined array values and have understood it. But for this one, I haven't find anything proper. Most of the search I found were related to const a = [] is an empty array or how to check if array is empty and so on.
So, if someone can explain or give any proper links to read, it will be very helpful.
Please let me know, if I should add anything else.
Share Improve this question edited Jul 6, 2024 at 3:39 Bergi 666k161 gold badges1k silver badges1.5k bronze badges asked Dec 12, 2019 at 11:26 Sunil ChaudharySunil Chaudhary 4,7433 gold badges25 silver badges42 bronze badges 5-
1
Empty is literally that - no data in that slot. It's not
undefined
, nornull
- the array is sparse. – VLAZ Commented Dec 12, 2019 at 11:27 - 2 Get references from stackoverflow./questions/50326047/… – Ayush Koshta Commented Dec 12, 2019 at 11:32
-
@VLAZ, Please correct me if I am wrong. It is something like: null means memory is allotted with value null (or reference points to null), undefined means memory location is allotted but no value exists (or reference is there but points to nowhere) but
empty means that memory is not even allotted (or reference doesn't exists at all)
? – Sunil Chaudhary Commented Dec 12, 2019 at 12:03 - Does this answer your question? What's the difference between empty items in a JavaScript array and undefined? – Fraction Commented Dec 12, 2019 at 12:07
-
@Sunil sort of. Whether memory is allocated or not in an array is an implementation detail. An array in JS is not necessarily given contiguous memory like with other languages, so a sparse array can definitely have the empty slots not even taking up space.
null
andundefined
are both values, so they are something that exists. However, it's possible that all bindings that are set tonull
are actually pointing to a single value, so you don't get multiple "copies" ofnull
. Not sure if that's done.undefined
could be an actual value or a lack of value - e.g.a = {}; a.foo
. – VLAZ Commented Dec 12, 2019 at 12:31
2 Answers
Reset to default 10Intro to sparse arrays
First a clarification what you've created is called a sparse array. To put it simply, sparse arrays are similar to normal arrays but not all of their indexes have data. In some cases, like JavaScript, this leads to slightly more significant handling of them. Other languages simply have a normal array of fixed length with some values that are "zero" in some sense (depends on what value can signify "nothing" for a specific array - might be 0
or null
or ""
, etc).
Empty slots
The empty slot in a sparse array is exactly what it sounds like - slot that is not filled with data. JavaScript arrays unlike most other implementations, are not fixed size and can even have some indexes simply missing. For example:
const arr = []; // empty array
arr[0] = "hello"; // index 0 filled
arr[2] = "world"; // index 2 filled
You will get an array with no index 1. It's not null
, nor it's empty, it's not there. This is the same behaviour you get when you have an object without a property:
const person = {foo: "hello"};
You have an object with a property foo
but it doesn't have, for example, a bar
property. Exactly the same as how the array before doesn't have index 1
.
The only way JavaScript represents a "value not found" is with undefined
, however that conflates
- "the property exists and the value assigned to it is
undefined
" - "the property does not exist at all"
Here as an example:
const person1 = { name: "Alice", age: undefined };
const person2 = { name: "Bob" };
console.log("person1.age", person1.age);
console.log("person2.age", person2.age);
console.log("person1.hasOwnProperty('age')", person1.hasOwnProperty('age'));
console.log("person2.hasOwnProperty('age')", person2.hasOwnProperty('age'));
You get undefined
when trying to resolve age
in either case, however the reasons are different.
Since arrays in JavaScript are objects, you get the same behaviour:
const arr = []; // empty array
arr[0] = "hello"; // index 0 filled
arr[2] = "world"; // index 2 filled
console.log("arr[1]", arr[1]);
console.log("arr.hasOwnProperty(1)", arr.hasOwnProperty(1));
Why it matters
Sparse arrays get a different treatment in JavaScript. Namely, array methods that iterate the collection of items will only go through the filled slots and would omit the empty slots. Here is an example:
const sparseArray = []; // empty array
sparseArray[0] = "hello"; // index 0 filled
sparseArray[2] = "world"; // index 2 filled
const arr1 = sparseArray.map(word => word.toUpperCase());
console.log(arr1); //["HELLO", empty, "WORLD"]
const denseArray = []; // empty array
denseArray[0] = "hello"; // index 0 filled
denseArray[1] = undefined; // index 1 filled
denseArray[2] = "world"; // index 2 filled
const arr2 = denseArray.map(word => word.toUpperCase()); //error
console.log(arr2);
As you can see, iterating a sparse array is fine, but if you have an explicit undefined
, in the array, then word => word.toUpperCase()
will fail because word
is undefined
.
Sparse arrays are useful if you have numerically indexed data that you want to run .filter
, .find
, .map
, .forEach
and so on. Let's illustrate again:
//some collection of records indexed by ID
const people = [];
people[17] = { id: 17, name: "Alice", job: "accountant" , hasPet: true };
people[67] = { id: 67, name: "Bob" , job: "bank teller", hasPet: false };
people[3] = { id: 3 , name: "Carol", job: "clerk" , hasPet: false };
people[31] = { id: 31, name: "Dave" , job: "developer" , hasPet: true };
/* some code that fetches records */
const userChoice = 31;
console.log(people[userChoice]);
/* some code that transforms records */
people
.map(person => `Hi, I am ${person.name} and I am a ${person.job}.`)
.forEach(introduction => console.log(introduction));
/* different code that works with records */
const petOwners = people
.filter(person => person.hasPet)
.map(person => person.name);
console.log("Current pet owners:", petOwners)
its just what it is empty
its neither undefined
or null
const a = [,,,,]
is same as const a = new Array(4)
here a
is an array with no elements populated and with only length
property
do this, let arr1 = new array()
and then console.log(arr1.length)
you'll get 0 as output. and if you do console.log(arr1)
you'll get [ <4 empty items> ]
if you change the length property of arr1 like this arr1.length = 4
you will have an empty array with it's length property = 4, but no items are populated so those slot will be empty
and if you do console.log(typeof(arr1[0])
you get undefined
only because there is no other possible types to show. And no methods of Array will be applied with an array with empty elements
so,
Empty array means an array with length property and with unpopulated slots
this is different from arrays with undefined
because in JS undefined
is a type and you can execute and have results by calling all array methods on it, whereas an array with empty
elememts have no type and no array methods can be applied on it.
本文标签: javascriptWhat is empty inside an array eg empty 215 5Stack Overflow
版权声明:本文标题:javascript - What is empty inside an array? e.g. [empty × 5] - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741887733a2403122.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论