W3School-JavaScript笔记四

JavaScript 数组用于在单一变量中存储多个值。
实例
var cars = ["Saab", "Volvo", "BMW"];
var car1 = "Saab";var car2 = "Volvo";var car3 = "BMW"; var cars=[car1,car2,car3];console.log(cars[1]);//Volvo

请不要最后一个元素之后写逗号(比如 "BMW",)。可能存在跨浏览器兼容性问题。


下面的例子也会创建数组,并为其赋值:
var cars = new Array("Saab", "Volvo", "BMW");
以上两个例子效果完全一样。无需使用 new Array()。
出于简洁、可读性和执行速度的考虑,请使用第一种方法(数组文本方法)。

var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
cars[0] = "Opel"; //修改指定的元素
document.getElementById("demo").innerHTML = cars[0];


var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
此时会按照顺序,在页面显示:"Saab", "Volvo", "BMW"

数组是一种特殊类型的对象。在 JavaScript 中对数组使用 typeof 运算符会返回 "object"。
但是,JavaScript 数组最好以数组来描述。


JavaScript 变量可以是对象。数组是特殊类型的对象。
正因如此,您可以在相同数组中存放不同类型的变量。
您可以在数组保存对象。您可以在数组中保存函数。你甚至可以在数组中保存数组

---------------------------------------------------------------------------

数组属性和方法:
var x = cars.length; // length 属性返回元素的数量
var y = cars.sort(); // sort() 方法对数组进行排序
var last = fruits[fruits.length - 1];


您也可以使用 Array.forEach() 函数:
var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
text += "<li>" + value + "</li>";
}

---------------------------------------------------------------------------

关于forEach:

源码描述:

/**
  * Performs the specified action for each element in an array.
  * @param callbackfn  A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
  * @param thisArg  An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  */
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;

如果在forEach里传了这个thisArg,那么当function被forEach回调时,这个this就指代这个thisArg;但如果不传,那么这个this,该是什么就是什么,跟这个thisArg就没关系了。

实例:

function testArrayIterator() {
    var arry = ["Cat", "Dog"];
    var idName = "demo";
    arry.forEach(buildItems, idName);
}

function buildItems(value, number, array) {
    if (number === 0) {
        tempValue = "<ul><li>" + value + "</li>";
    } else if (number === array.length - 1) {
        tempValue += "<li>" + value + "</li></ul>";
        document.getElementById(this).innerHTML = tempValue;
        tempValue = "";
    } else {
        tempValue += "<li>" + value + "</li>";
    }
}
原文地址:https://www.cnblogs.com/bruceChan0018/p/14920601.html