Home >Web Front-end >Front-end Q&A >Can objects be included in a javascript array?

Can objects be included in a javascript array?

青灯夜游
青灯夜游Original
2022-03-28 16:20:393422browse

Javascript arrays can contain objects. A JavaScript array is a collection of data arranged in order. The array can contain any type of data, that is, there is no limit on the type of array elements, which can be numbers, strings, arrays, Object, etc.

Can objects be included in a javascript array?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript arrays can contain objects.

An array (Array) is a collection of data arranged in order. Each value in the array is called an element, and the array can contain any type of data.

Example:

let arr = [1,'hello',true,[1,2],{name: 'Bob',age:20}];
console.log(arr);

Can objects be included in a javascript array?

It can be seen that when defining an array and assigning a value, the value of the array element can be a number, string, or Boolean Value, array, object and other types.

Simply put, there is no restriction on the type of array elements.

Extended knowledge: Pseudo-class array

Pseudo-class array, also known as class array, is an object similar to an array structure. To put it simply, the object's attribute name is a non-negative integer, starting from 0, increasing in order, and including the length attribute. It should also ensure that its value is dynamically consistent with the number of ordered subscript attributes to facilitate pseudo-classes. Array iteration. The well-known jQuery object is a pseudo-array.

Example

In the following example, obj is an object literal. When assigning it using an array subscript, JavaScript no longer treats it as an array subscript, but instead It is regarded as the property name of the object.

var obj = {};  //定义对象直接量
obj[0] = 0;
obj[1] = 1;
obj[2] = 2;
obj.length = 3;
console.log(obj["2"]);  //返回2

It is equivalent to an object literal.

var obj = {
    0 : 0,
    1 : 1,
    2 : 2,
    length : 3
};

Because numbers are illegal identifiers, you cannot use dot syntax to read and write attributes.

console.log(obj.0);

Instead, use square bracket syntax to read and write properties.

console.log(obj["2"]);

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of Can objects be included in a javascript array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn