javascript js操纵数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript js操纵数组相关的知识,希望对你有一定的参考价值。

//add to the end of the array
var numbers = [1,2,3,4,5,6];
numbers[numbers.length] = 7;
console.log(numbers); // [1, 2, 3, 4, 5, 6, 7]
//the number 7 will be added to the end of the array 
//since numbers.length = 6 which is the seventh spot in the array (0 1 2 3 4 5 6)

//ADDING
//PUSH to the end of the array
var numbers = [1, 2, 3];
numbers.push(4, 5);
console.log(numbers); // [1, 2, 3, 4, 5]

//UNSHIFT: put at the beginning of the array
var numbers = [1, 2, 3];
numbers.unshift(4, 5);
console.log(numbers); // [4, 5, 1, 2, 3]

//REMOVING
//POP away from the end of the list and RETURN it!
var numbers = [1, 2, 3];
var poppedNumber = numbers.pop();
console.log(numbers); // [1, 2]
console.log(poppedNumber); // 3

//SHIFT to remove the first item from the array
var numbers = [1, 2, 3];
var shiftedNumber = numbers.shift();
console.log(numbers); // [2, 3]
console.log(poppedNumber); // 1

//Use PUSH and SHIFT to create a queue, first in first out, fifo
//SHIFT out the first in the array and PUSH a new one on to the end.

//JOIN
//takes an array and RETURNS a STRING of all the items in the array 
//separated by a supplied char, such as a comma (a great way to display all the items in
//an array in a single line.)
var daysInWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var daysString = daysInWeek.join(', ');
console.log(daysString); //Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

//CONCAT
//joins two arrays together into a new array. The two original arrays are unchanged
var currentStudents = ['Joan', 'John', 'Joaquin'];
var newStudents = ['Sam', 'Tracy', 'Tiago'];
var allStudents = currentStudents.concat(newStudents);//newStudents is added to the end of currentStudents
console.log(allStudents);//Joan, John, Joaquin, Sam, Tracy, Tiago

//INDEXOF
//Lets you search an array for a particular value and returns the position.
var fruit = ['apple', 'orange', 'grapefruit'];
var position = fruit.indexOf('apple');//position = 0
console.log('The value is: ', fruit[position]) //apple
//if item is not in the array, it returns a -1, which is useful to see if a particular item is in an array or not.

//SLICE
//copy array
var pens = ['red', 'blue', 'green', 'black'];
var newPens = pens.sclice(); //console.log(newPens); ['red', 'blue', 'green', 'black']

以上是关于javascript js操纵数组的主要内容,如果未能解决你的问题,请参考以下文章

Javascript更改/迁移/操纵HTML表格(Table)内容案例 (备选表格案例)

Javascript更改/迁移/操纵HTML表格(Table)内容案例 (备选表格案例)

JavaScript-14(操纵属性和window)

js函数式编程1-1

21JavaScript笔记

Javascript:操纵状态栏以显示日期?