首页 > 其他 > 详细

Array

时间:2019-04-10 19:55:16      阅读:109      评论:0      收藏:0      [点我收藏+]

创建数组

var fruits = [apple, banana]

通过索引访问数组元素

var first = fruits[0]

var last = fruits[fruits.length - 1]

遍历数组

fruits.forEach(function (item, index, array) {
    console.log(item, index);
})

添加元素到数组尾部

var newLength = fruits.push(Orange);
// newLength:3; fruits: ["Apple", "Banana", "Orange"]

删除数组末尾的元素

var last = fruits.pop(); // remove Orange (from the end)
// last: "Orange"; fruits: "Apple", "Banana"];

删除数组头部元素

var first = fruits.shift(); // remove Apple from the front
// first: "Apple"; fruits: ["Banana"];

添加元素到数组头部

var newLength = fruits.unshift(Strawberry) // add to the front
// ["Strawberry", "Banana"];

找出某个元素在数组中的索引

fruits.push(Mango);
// ["Strawberry", "Banana", "Mango"]

var pos = fruits.indexOf(Banana);
// 1

通过索引删除某个元素

var removedItem = fruits.splice(pos, 1); // this is how to remove an item

// ["Strawberry", "Mango"]

从一个索引位置删除多个元素

var vegetables = [Cabbage, Turnip, Radish, Carrot];
console.log(vegetables); 
// ["Cabbage", "Turnip", "Radish", "Carrot"]

var pos = 1, n = 2;

var removedItems = vegetables.splice(pos, n);
// this is how to remove items, n defines the number of items to be removed,
// from that position(pos) onward to the end of array.

console.log(vegetables); 
// ["Cabbage", "Carrot"] (the original array is changed)

console.log(removedItems); 
// ["Turnip", "Radish"]

复制一个数组(深拷贝)

var shallowCopy = fruits.slice(); // this is how to make a copy 
// ["Strawberry", "Mango"]

数组的索引是从0开始的,最后一个元素的索引等于该数组的长度减1。如果指定的索引是一个无效值,并不会报错,而是返回undefined

var arr = [this is the first element, this is the second element, this is the last element];
console.log(arr[0]);              // 打印 ‘this is the first element‘
console.log(arr[1]);              // 打印 ‘this is the second element‘
console.log(arr[arr.length - 1]); // 打印 ‘this is the last element‘

在数组中已数字开头的属性不能用点开头引用

var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
console.log(years.0);   // 语法错误
console.log(years[0]);  //
renderer.3d.setTexture(model, character.png);     // 语法错误
renderer[3d].setTexture(model, character.png);  //

 

Array

原文:https://www.cnblogs.com/sonwrain/p/10685529.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!