JavaScript

JavaScript中的数组和对象

1 阵列和物件

这是我在YouTube上看到一个台湾哥们讲JavaScript基础时提到的概念,原来他们那边是这么命名这两个术语的。比较有意思,一下子就掌握和记住了这两个之间的最基本区别。数组–阵列,用方括号[],对象–物件,用花括号{}。

当然,再回想一下当初入行时,跟着小布老师学习Oracle的时候,他推荐了一本英文原版书,大名鼎鼎的Tom Kyte的Oracle 9i编程艺术,我跟着小布老师的节奏,尝试着捏着鼻子人模人样的读起英文技术书籍。Tom在书中讲到,RAID[Redundant Array of Independent Disks]技术,业内习惯叫磁盘阵列,完整的翻译,我觉得应该叫冗余独立磁盘阵列。说不定,这个术语就是沿用了台湾那边的叫法。

那个YouTube频道:布鲁斯前端

https://www.youtube.com/watch?v=1pYtVwIAvhY&t=1075s

2 数组的数据类型是object

在JavaScript中,数组本身的数据类型却是对象object。

const cars['BMW','NISSAN','Benz'];
console.log(typeof cars);    //object

Arrays are a special type of objects. The typeof operator in JavaScript returns “object” for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its “elements”. In this example, cars[0] returns BMW。

引自w3schools:https://www.w3schools.com/js/js_arrays.asp

3 数组的元素可以是对象

数组的元素可以是对象,在JavaScript中,数组、函数的数据类型都是object。因此,数组的元素可以是一个对象,也可以是一个函数,甚至还可以是其它的一个数组。

<!DOCTYPE html>
<html lang="en">
<head>
    <!--@Author:asher
    @Date:2021/7/9 08:01   -->
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>JavaScript Arrays</h2>
<p>Array.forEach() calls a function for each array element.</p>
<p id="demo"></p>
<p id="demo2"></p>
<script>
    const fruits = ['apple', 'orange', 'grape', 'pear'];
    let text='<ul>';
    fruits.forEach(myFunc);
    text+='</ul>';
    document.getElementById('demo').innerHTML = text;

    const newArray = [myFunc(), fruits];

    document.getElementById('demo2').innerHTML = newArray;
    function myFunc(value) {

        text+='<li>'+value+'</li>';
    }
</script>

</body>
</html>

4 数组添加元素

语法1:数组名.push(‘新元素’); 数组名.push(‘新元素1′,’新元素2’);

语法灵活,可以一次添加1个,也可以添加多个。如果添加的元素是对象的话,则直接写对象名,不需要单引号或者是双引号。

语法2: 数组名[数组名.length]=’新元素’;

语法3:数组名[100]=’新元素’; 当索引下标超出数组现有长度时,添加不会失败,也不会像Java那样抛出IndexOutOfArrayLenth的错误。只是,此时该新添加的元素被放到一个undefined ‘hole’ in the array.

WARNING !

Adding elements with high indexes can create undefined “holes” in an array:

4.5补充(2021.07.10) 数组头、尾部操作

a 头部删除/添加元素shift()/unshift()

unshift()添加新的元素之后,原有的元素依次向后移动1个位置;返回值是头部添加元素之后,新数组的长度。

shift()删除数组头部元素之后,原有的元素依次向前移动1个位置;返回值是头部元素;

b 尾部添加/删除元素push()/pop()

尾部添加元素push(),返回值是新数组的长度;

数组尾部元素删除pop(),返回值是尾部的元素;

5 避免使用new Array()来创建数组

The new keyword only complicates the code. It can also produce some unexpected results:

// This creates an array with two elements (40 and 100):
const points = new Array(40, 100);  

// This creates an array with 40 undefined elements !!
const points = new Array(40);  

6 数组和对象的区别

In JavaScript, arrays use numbered indexes.

In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

Arrays use numbers to access its “elements”.数组使用基于数字的索引下标来访问元素:

const person=['John','Kate'];
let name = person[0];

Objects use names to access its “members”. 对象使用基于key值的下标来访问数据:

const person={firstName:"John",lastName:'Kate',age:40};
let name=person.firstName;

7 When to Use Arrays. When to use Objects.

  • You should use objects when you want the element names to be strings (text).
  • You should use arrays when you want the element names to be numbers.

8 How to Recognize an Array

怎么判断一个对象是不是一个数组?

由于JavaScript认为数组的数据类型是object,那么我改如何判断一个数组的数据类型是数组呢?

const cars = ['BMW','Benz'];
typeof cars ;//结果是object,这时怎么判断它是数组呢?

方法1:To solve this problem ECMAScript 5 defines a new method Array.isArray():

// To solve this problem ECMAScript 5 defines a new method Array.isArray():
Array.isArray(cars);    //返回结果是true,说明是数组

方法2:The instanceof operator returns true if an object is created by a given constructor:

//The instanceof operator returns true if an object is created by a given constructor:
cars instanceof Array;// return true.

方法3:利用constructor property来判断

2021年7月11日补充,看官网https://www.w3schools.com/js/js_typeof.asp学习到的。

const fruits = ['apple','mongo'];
let isArray = isArray(fruits);
function isArray(array){
  return array.constructor.toString().indexOf("Array") > -1;
}

或者利用constructor property的一种更简单的判断方式:

const fruits = [1,2,3];
let x = isArray(fruits);
function isArray(array){
  return array.constructor === Array;
}

9 数组的自动toString

JavaScript automatically converts an array to a comma separated string when a primitive value is expected.

This is always the case when you try to output an array.

These two examples produce the same result:

All JavaScript objects have a toString() method.

这一点儿,跟Java有异曲同工之妙。我们在Java中,有时为了输出打印对象,我们就得重写@Override该对象所在类的toString()方法。当然,该方法来自于Object类。

留言